Reputation: 9
I was trying to write a code including a function in order to find numbers that are complete(perfect number:the number which is = its denominator's summation) but I had some problem with it...would you help me?
L=[]
def denominator(n):
k=1
while(int(k) < int(n)):
s=int(n%k)
if(s==0):
L+=[s]
k+1
return L
def isPerfect(n):
return denominator(n)
a=sum(L)
return(a==n)
n=input("enter a number:")
if(isPerfect(n)):
print("it is perfect.")
else:
print("it's not perfect.")
Upvotes: 0
Views: 452
Reputation: 1351
I think, this is more pythonic code for this problem:
if sum([x for x in range(1,n) if n%x==0])==n and n>0:
print "complete"
else:
print " Not complete"
Upvotes: 1
Reputation: 36695
You have a lot of mistakes in your code. L
has to be defined in denominator
; you has to add k
not s
to L
; in while
you has to increment k
; denominator
has to return list of dividers; you has to convert n
to int after input and it is enough to check dividers until [n/2+1]. After removing these misprints your code will work:
def denominator(n):
L = []
k=1
while(k < int(n/2.+1)):
if(n%k==0):
L+=[k,]
k=k+1
return L
def isPerfect(n):
L = denominator(n)
a=sum(L)
return(a==n)
n=input("enter a number:")
if(isPerfect(int(n))):
print("it is perfect.")
else:
print("it's not perfect.")
However you may reduce your code like:
def isPerfect(n):
if (n < 1): return False
sum = 0
for k in range(1, int(n/2+1)):
if n % k == 0:
sum += k
return sum == n
print(isPerfect(6), isPerfect(28))
Upvotes: 0
Reputation: 3094
With @Serenity's answer and the comments to your post I think you have all that you need to correct the errors in your code. Let me also give you this nearly one-liner that does what you want:
def is_perfect(n):
return False if n <= 0 else (sum([s for s in range(1, n) if n%s == 0]) == n)
Upvotes: 1