Python 3.x 如何在列表中找到素数最大的数?
我想写一个程序,接收10个条目,最后它应该打印出素数因子数量最多的数字,以及输出中素数因子的数量。而且,如果某些输入具有相同的条件,程序将打印最大的输入 我编写的代码执行除最终条件之外的所有条件。 当我想把较大的数作为输出时,如果两个数具有相同的素数因子,我应该如何编写代码? 例如,678和84都有3个基本因子。我的代码的输出是84,而我希望输出是678,数字越大 输入: 123 43 54 12 76 84 98 678 543 231 正确输出: 678 3 但是我的输出: 84 3Python 3.x 如何在列表中找到素数最大的数?,python-3.x,Python 3.x,我想写一个程序,接收10个条目,最后它应该打印出素数因子数量最多的数字,以及输出中素数因子的数量。而且,如果某些输入具有相同的条件,程序将打印最大的输入 我编写的代码执行除最终条件之外的所有条件。 当我想把较大的数作为输出时,如果两个数具有相同的素数因子,我应该如何编写代码? 例如,678和84都有3个基本因子。我的代码的输出是84,而我希望输出是678,数字越大 输入: 123 43 54 12 76 84 98 678 543 231 正确输出: 678 3 但是我的输出: 84 3 当您将
当您将素数最多的数字附加到列表n中时,您将它们存储为字符串而不是整数。因此,当您在n上执行max函数时(其中包含84678和231),将返回84。我建议您在存储为n时使用int转换数字,然后对其执行maxfunction。只需调整代码,如下所示:
for t in index_of_same:
n.append(int(a[t]))
您的代码在IMO中很麻烦,因此我建议使用一个更简单的版本:
def getNumOfFactors(n):
num = 0
factor = 1
while n > 1:
factor += 1
if n % factor == 0:
num += 1
n /= factor
while n % factor == 0:
n /= factor
return num
def getMaxValue(values):
factors = [getNumOfFactors(n) for n in values]
tuples = zip(factors,values)
sorted_tuples = sorted([tuple for tuple in tuples],key=lambda x: x[0])
max_tuples = [tuple for tuple in sorted_tuples if tuple[0] == sorted_tuples[-1][0]]
sorted_max_tuples = sorted([tuple for tuple in max_tuples],key=lambda x: x[1])
return sorted_max_tuples[-1]
maxValue = getMaxValue([123,43,54,12,76,84,98,678,543,231])
print(maxValue)
def getNumOfFactors(n):
num = 0
factor = 1
while n > 1:
factor += 1
if n % factor == 0:
num += 1
n /= factor
while n % factor == 0:
n /= factor
return num
def getMaxValue(values):
factors = [getNumOfFactors(n) for n in values]
tuples = zip(factors,values)
sorted_tuples = sorted([tuple for tuple in tuples],key=lambda x: x[0])
max_tuples = [tuple for tuple in sorted_tuples if tuple[0] == sorted_tuples[-1][0]]
sorted_max_tuples = sorted([tuple for tuple in max_tuples],key=lambda x: x[1])
return sorted_max_tuples[-1]
maxValue = getMaxValue([123,43,54,12,76,84,98,678,543,231])
print(maxValue)