仅使用循环来压缩程序

时间:2017-03-17 17:27:50

标签: python python-3.x

我的任务是创建一个程序,找到定义范围内的所有正整数。目前我在学校,所以我只能使用循环和功能来使其工作(另请注意,我刚开始学习使用函数。

我上传了它的图片。

我的问题在于,当我运行它而不是仅打印正值时,它还打印出10 000个空白行。我希望情况不是这样。 我认为它与第二个其他陈述有关。

enter image description here

1 个答案:

答案 0 :(得分:0)

def getDivisors(number):
    divList = []
    for x in range(1,number):
        if number % x == 0:
            divList.append(x)
    return divList

def isPerfectNumber(divList,number):
    if sum(divList) == number:
        return True
    else:
        return False

for x in range(2,10001):
    divList = getDivisors(x)
    if isPerfectNumber(divList,x):
        print(x,divList)

看起来代码有效。我也打印出了分区列表,这样你就可以检查自己的数字。

这是我的输出:

6 [1,2,3]

28 [1,2,4,7,14]

496 [1,2,4,8,16,31,62,124,248]

8128 [1,2,4,8,16,32,64,127,254,508,1016,2032,4064]