Python for maximum pairwise product(最大配对乘积的Python)
本文介绍了最大配对乘积的Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
n = int(input("Enter the number of elements in the array (2-200,000):"))
a = [int(x) for x in input("Enter all numbers of the sequence with only non-negative intergers not exceeding 100,000:").split()]
c = list()3
for i in range(0,n):
for j in range (1,n):
if a[i] != a[j]:
m = a[i]*a[j]
c.append(m)
else:
continue
print(max(c))
此代码可以工作。但是,我想定义一个函数来自动计算以下代码中第5行的最大乘积。
def MaxPairwiseProduct(n,a,c):
for i in range(0,n):
for j in range (1,n):
if a[i] != a[j]:
m = a[i]*a[j]
c.append(m)
else:
continue
Product = max(c)
return Product
n = int(input("Enter the number of elements in the array (2-200,000):"))
a = [int(x) for x in input("Enter all numbers of the sequence with only non-negative intergers not exceeding 100,000:").split()]
c = list()
MaxPairwiseProduct(n,a,c)
我重写了该函数,但它不起作用。它显示"IndentationError:预期为缩进块"
推荐答案
# Uses python3
def MaxPairwiseProduct(n,a,c):
for i in range(0,n):
for j in range (1,n):
if a[i] != a[j]:
m = a[i]*a[j]
c.append(m)
else:
continue
Product1 = max(c)
return Product1
def MaxPairwiseProductFast(n,a):
max_index1 = -1
for i in range(0,n):
if a[i] > a[max_index1]:
max_index1 = i
else:
continue
#the value of the other index should be different compared to the #first, else it will assume the same indices for both the max
max_index2 = -2
for j in range(0,n):
if a[j] > a[max_index2] and a[j] != a[max_index1]:
max_index2 = j
else:
continue
Product2 = a[max_index1]*a[max_index2]
return Product2
n = int(input("Enter the number of elements in the array (2-200,000):"))
a = [int(x) for x in input("Enter all numbers of the sequence with only non-negative intergers not exceeding 100,000:").split()]
c = list()
print('The max value by regular algorithm:', MaxPairwiseProduct(n,a,c))
print('The max value by faster algorithm:', MaxPairwiseProductFast(n,a))
此代码包含计算最大值的第二种算法。
这篇关于最大配对乘积的Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:最大配对乘积的Python
基础教程推荐
猜你喜欢
- 合并具有多索引的两个数据帧 2022-01-01
- 如何在Python中绘制多元函数? 2022-01-01
- 哪些 Python 包提供独立的事件系统? 2022-01-01
- 症状类型错误:无法确定关系的真值 2022-01-01
- 使用Python匹配Stata加权xtil命令的确定方法? 2022-01-01
- 将 YAML 文件转换为 python dict 2022-01-01
- 使用 Google App Engine (Python) 将文件上传到 Google Cloud Storage 2022-01-01
- 使 Python 脚本在 Windows 上运行而不指定“.py";延期 2022-01-01
- Python 的 List 是如何实现的? 2022-01-01
- 如何在 Python 中检测文件是否为二进制(非文本)文 2022-01-01