首页 > 解决方案 > 如何将列表中的数字与列表中下一个数字的因子之和进行比较?

问题描述

我想将列表中的数字与列表中下一个数字的因子之和进行比较

例如我有一个列表:[15,9,220,284]:

A=15 and the sum of the factors is = 1+3+5= 9
B=9 and the sum of the factors is 4 
so the program should return 0
A=220 and the sum of the factors is 284
B=284 and the sum of the factors is 220
so the program should return 1

标签: python

解决方案


你可以尝试这样的事情,基于这个divisors(n)似乎是计算数字因子最快的函数,我用它证明了它n=600851475143并且它需要0.2790100000020175 seconds运行脚本1000000时间,而其他人则比16 seconds使用相同的数字需要更多:

def divisors(n):
    # get factors and their counts
    factors = {}
    nn = n
    i = 2
    while i*i <= nn:
        while nn % i == 0:
            factors[i] = factors.get(i, 0) + 1
            nn //= i
        i += 1
    if nn > 1:
        factors[nn] = factors.get(nn, 0) + 1

    primes = list(factors.keys())

    # generates factors from primes[k:] subset
    def generate(k):
        if k == len(primes):
            yield 1
        else:
            rest = generate(k+1)
            prime = primes[k]
            for factor in rest:
                prime_to_i = 1
                # prime_to_i iterates prime**i values, i being all possible exponents
                for _ in range(factors[prime] + 1):
                    yield factor * prime_to_i
                    prime_to_i *= prime

    # in python3, `yield from generate(0)` would also work
    for factor in generate(0):
        yield factor
        
lis=[15,9,220,284]
for x, y in zip(lis, lis[1:]):
    print('with ',x,' and ', y,': ' )  
    if (sum(list(divisors(x))[:-1])==y) and (sum(list(divisors(y))[:-1])==x):
        print('1\n')
    else:
        print('0\n')

输出:

with  15  and  9 : 
0

with  9  and  220 : 
0

with  220  and  284 : 
1

或者您可以将其保存在 dict 中可能更实用:

lis=[15,9,220,284]
dct={}
for x, y in zip(lis, lis[1:]):  
    key=str(x)+'-'+str(y)
    if (sum(list(divisors(x))[:-1])==y) and (sum(list(divisors(y))[:-1])==x):
        dct.update({key:1})
    else:
        dct.update({key:0})
        
print(dct)

输出:

{'15-9': 0, '9-220': 0, '220-284': 1}

推荐阅读