Skip to main content
 首页 » 编程设计

python之检查字典中的任何键是否匹配任何值

2024年11月24日15lovecherry

我正在尝试解决这个问题:

Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers.

For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.

Evaluate the sum of all the amicable numbers under 10000.

我想出了一个字典,其中包含 0 到 9999 的所有数字 x:d(x),如下所示:

sums = {x:sum(alecproduct.find_factors(x))-x for x,y in enumerate(range(10**4))} 

其中 alecproduct.findfactors 是我自己的模块中的一个函数,它返回一个数字的所有因数列表

不过,我不确定从这里到哪里去。我试过遍历字典并从每个 k-v 对中创建元组,如下所示:

for k,v in sums.items(): 
    dict_tups.append((k,v)) 

但我认为这对我没有帮助。关于如何检测是否有任何字典键与任何字典值匹配的任何建议?

编辑 - 我的解决方案基于 6502 的回答:

sums,ap = {x:sum(find_factors(x))-x for x,y in enumerate(range(10**4))}, [] 
 
for x in sums: 
    y = sums[x] 
    if sums.get(y) == x and x != y: 
        ap.append(x) 
 
print(ap) 
print('\nSum: ', sum(ap)) 

请您参考如下方法:

你的问题几乎已经解决了……把所有的夫妇都赶出去:

for x in my_dict: 
    y = my_dict[x] 
    if my_dict.get(y) == x: 
        # x/y is an amicable pair 
        ... 

请注意,每对将被提取两次(x/y 和 y/x)和完全数(除数之和的数字)只有一次;从你的问题文本中不确定 6/6 是否被认为是友好的一对。