想要找到除数最大的数,但它会继续打印最后输入的数字及其除数

时间:2019-07-02 15:27:06

标签: python list python-3.6 primes

目标是计算三个数的质数,并打印具有最大质数的质数和质数,但是我的代码将打印第三个质数和质数,即使它不是数量最多的质数主要除数,我该怎么办?

def walk_dir(dir_path):
    dir_files = dbutils.fs.ls(dir_path)
    excel_files = []
    for file in dir_files:
        if file.isDir():
            excel_files.extend(walk_dir(file.path))
        elif file.path.endswith('.xlsx'):
            excel_files.append(os.path.join('/dbfs', file.path[5:])
    return excel_files

all_excel = walk_dir('/raw/internal/srange/2018_11_30_00_22_11/')

3 个答案:

答案 0 :(得分:1)

首先,您可以通过删除for循环来简化prime_counter()的数字:

def prime_counter(n):
    l1 = []
    for b in range(1,n+1):
        if n % b == 0:
            l1.append(b)
    return l1

接下来,您可以使用列表推导来更快地计算素数:

import numpy as np

l = []
for i in range(0, 3):
    x = int(input())
    l.append(x)

# We save the number of divisors for each number of l    
number_prime_divisor = [len(prime_counter(x)) for x in l]

# Now we just have to look the index with the max number of prime divisors
# using np.argmax
l[np.argmax(number_prime_divisor)]

一个简单的例子:

l = [4,5,6]

number_prime_divisor = [len(prime_counter(x)) for x in l]
print(number_prime_divisor)
[3, 2, 4]

print(l[np.argmax(number_prime_divisor)])
6

答案 1 :(得分:0)

在这部分代码中,您将在每次比较之前用[]覆盖l2:

28.0

所以:

for i in range(0, len(l)):
  l2 = []
  if len(prime_counter(l[i])) > len(l2):
      l2 = prime_counter(l[i])
只要prime_counter返回包含一个或多个元素的列表(因为l2为空),

将为True

要在for循环之前修复此初始化l2,并将i存储在辅助变量中

len(prime_counter(l[i])) > len(l2)

答案 2 :(得分:0)

通过实现递归函数,您可以在此处大大简化逻辑并提高性能:

def prime_counter(n, pd, out):

    quot = n/pd

    if quot==1:
        out.append(pd)
        return out
    if int(quot)==quot:
        out.append(pd)
        return prime_counter(quot, 2, out)
    else:
        return prime_counter(n, pd+1, out)

numbers = [12,25,100]

test = {n: prime_counter(n, 2, []) for n in numbers}

收益:

{12: [2, 2, 3], 25: [5, 5], 100: [2, 2, 5, 5]}

然后很容易确定最大除数的数量以及主要除数的数量(您将需要弄清楚如何打破平局):

most_primes = max(test, key=lambda x: len(test[x]))
number_of_primes = len(test[most_primes])

礼物:

100
4