简体   繁体   English

从整数范围内查找完全整数列表

[英]finding a list of perfect integers from a range of integer numbers

the user will input a arbitrary range where the end number is the number up to what the user wants perfect numbers from those numbers and append the numbers in a list and print the list or the list elements... Sample CODE: sum_1=0 sum_2=0 b=[]用户将输入一个任意范围,其中结束数字是用户想要从这些数字中得到完美数字的数字,并将数字附加到列表中并打印列表或列表元素...示例代码:sum_1=0 sum_2 =0 b=[]

a=range(1,int(input('enter_num_upto you want perfect num')))

for i in a:
    for items in range(1,i):
        if(i%items)==0:
            sum_1=sum_1+items
            sum_2=sum_2+items+i
        
        if sum_1==i and (sum_2//2)==i:
                   b.append(i)
               
    for j in b:
         print(j)
    

the code runs without errors but it doesn't display any outputs..... please mark my mistakes and explain the correct logics THANKS IN ADVANCE代码运行没有错误,但它不显示任何输出..... 请标记我的错误并解释正确的逻辑 感谢提前

I think the problem is that you haven't defined the list "b".我认为问题在于您尚未定义列表“b”。 I'd suggest that after you define我建议在你定义之后

a=range(1,int(input('enter_num_upto you want perfect num')))

define b as将 b 定义为

b=[]

This will tell the program that a list "b" exists, which you can then append items to.这将告诉程序存在列表“b”,然后您可以将项目附加到该列表中。 You can't append items to a list that doesn't exist yet.您不能将项目附加到尚不存在的列表中。

The same thing should go for the 2 variables sum_1 and sum_2, you cannot define them conditionally in an "if statement", therefore you should define them at the beginning of your program, right after you define b同样的事情应该适用于 2 个变量 sum_1 和 sum_2,你不能在“if 语句”中有条件地定义它们,因此你应该在你的程序开始时定义它们,在你定义 b 之后

sum_1 = 0
sum_2 = 0

As for the logic of your code, I suggest you don't need a sum_2, after going through the for loop that makes sum_1, check if sum_1 is equal to i.至于你的代码的逻辑,我建议你不需要sum_2,经过使sum_1的for循环后,检查sum_1是否等于i。 But make sure whenever you use "range", you set the end as the number after you want to end it at.但是请确保无论何时使用“范围”,都将结尾设置为要结束的数字。 For example if you want the range to start at 1 and end at I, use range(1,i+1).例如,如果您希望范围从 1 开始并在 I 结束,请使用 range(1,i+1)。 This is only for your input.这仅用于您的输入。 Make sure to set sum_1 back to 0 after every iteration aswell.确保在每次迭代后将 sum_1 设置回 0。

so:所以:

a=range(1,int(input('enter_num_upto you want perfect num'))+1)
b=[]
sum_1=0

for i in a:
    for item in range(1,i):
       if (i%item)==0:
          sum_1= sum_1+item
     
    if sum_1==i:
        b.append(i)
    
    sum_1=0



for j in b:
   print(j)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM