使用Python中的字典查找给定范围内的友好数字

时间:2019-06-05 04:43:40

标签: python

我正在尝试使用Python中的字典查找给定范围内的友好数字。

这是我的代码,无法过滤其键和值是友好数字的字典项。例如,在输出从1到1000的每个数字的适当除数的总和后的输出中,诸如(220,284),(284,220)之类的项目,其中220和284是友好数字。通过这种方式,我试图找到介于1到1000之间的所有此类友好数字。


    index1 = 1
    index2 = 1000
    lst = []
    dict = {}
#     for i in range(index1, index2+1):
#         lst.append(i)

    print("Finding Amicable numbers..")
    for index in range(index1, index2+1):
        sum = 0
        for i in range(1, index):
            if index % i == 0:
                sum += i
            dict[index] = sum
        #print("Number = {}, Sum = {}".format(index, sum))
    print(dict.items())
    #print("k, v")
    #for k,v in dict.items():


    isAmicable2()

Output:
```Finding Amicable numbers..
dict_items([(2, 1), (3, 1), (4, 3), (5, 1), (6, 6), (7, 1), (8, 7), (9, 4), (10, 8), (11, 1), (12, 16), (13, 1), (14, 10), (15, 9), (16, 15), ...................,(220, 284),(221, 31), (222, 234),..................,(280, 220)..........................................................................................(991, 1), (992, 1024), (993, 335), (994, 734), (995, 205), (996, 1356), (997, 1), (998, 502), (999, 521), (1000, 1340)])```


I have tried breaking the code into chunks and loop through but couldn't figure the way to do the same. 


    num1 = 220
    num2 = 284

    amicable1 = 0
    sum = 0
    for index1 in range(1, 220):
        if num1 % index1 == 0:
            sum += index1
        amicable1 = sum
    print(amicable1)

    amicable2 = 0
    sum2 = 0
    for index1 in range(1, 284):
        if num2 % index1 == 0:
            sum2 += index1
        amicable2 = sum2
    print(amicable2)

    if num1 == amicable2:
        print("{} and {} are amicable".format(num1, num2))

Expected results:
Print the pair of amicable numbers in a given range.

1 个答案:

答案 0 :(得分:0)

如果您已经制作了包含数字适当因子之和的字典,则可以只查找一个数字,然后查找该查找的结果。换句话说:

d = SomeDictWithSums

if d[d[n]] == n:
   # n is either amicable or a perfect number.
   # for example d[220] == 284 
   # and d[284] == 220

要剔除完美数字,只需测试:

n != d[n]

您可以将这两个代码合并在一起,以生成类似以下内容的友好数字元组:

index1 = 1
index2 = 1000
lst = []

print("Finding Amicable numbers..")
d = {}
for index in range(index1, index2+1):
    s = sum(i for i in range(1, index) if index % i == 0)
    d[index] = s

amicables = [(n, d[n]) for n in d if d[n] in d and d[d[n]] == n and n != d[n] ] 
print(amicables)

结果

Finding Amicable numbers..
[(220, 284), (284, 220)]

消除条件and n != d[n]将使您友善和完美:

[(6, 6), (28, 28), (220, 284), (284, 220), (496, 496)]