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

标签 python dictionary

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

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/yy/x)和完全数(除数之和的数字)只有一次;从你的问题文本中不确定 6/6 是否被认为是友好的一对。

关于python - 检查字典中的任何键是否匹配任何值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54997480/

相关文章:

Java:如何原子地替换映射中的所有值?

python - 绘制包含列表作为值的字典的所有键(python)

python - 从变量中删除值的最佳方法?创建数组,或使用正则表达式?或者用Xpath?

python - Django - 将列表转换为 Q 对象的组合 OR 的正确方法

python - flask 导入错误 : No Module Named Flask

dictionary - 你如何遍历两个字典并在同一路径上获取值?

ios - 带有数组值的 Swift 字典

python-3.x - 无法将网络抓取输出作为字典返回

python - 如何使用nltk找出英语中是否存在单词

python - 字典总是在 python 中存储哈希的最有效方式吗?