python - 如何将列表中的数字与列表中下一个数字的因子之和进行比较?
问题描述
我想将列表中的数字与列表中下一个数字的因子之和进行比较
例如我有一个列表:[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
解决方案
你可以尝试这样的事情,基于这个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}
推荐阅读
- mongodb - 有什么方法可以将 MongoDB 连接到 Druid?
- tensorflow - 张量在从 TF 到 TFlite 的转换过程中丢失了它们的维度
- r - 如何连接 2 个数据框,其中 R 中的列值不相等
- python - 如果列名与数据框名称相同,则从多个数据框中选择特定列
- python-3.x - 在 PyQT5 上看不到描绘国际象棋的方法
- mysql - MySql.Data.MySqlClient.MySqlException:'重复字段''
- azurekinect - Azure Kinect:如何找到 Windows 设备 ID
- julia - (Julia 1.x) BoundsError 使用 pmap?
- prestashop - 如何在 Prestashop 1.7.5 中将生成的条形码附加到电子邮件中
- typescript - Vue 和 Typescript 3.5.3 抱怨 `ComputedOptions
`