Why Is My Code Displaying The Wrong Output?
Solution 1:
Sorry for the confusion regarding my previous answer. The problem was that you were appending n
instead of i
in myList.append(n)
. Moreover, you could simply use sum
to sum your list.
Your output was wrong because you were appending the number n
and hence when you do sum=sum+myList[i]
, you were just adding n
to the sum three times because instead of adding 1, 2, 3 to sum
, you were adding 6, 6, 6.
n=int(input())
myList=[]
for i inrange(1,n):
if n%i==0:
myList.append(i)
ifsum(myList)==n:
print("Yes")
else:
print("No")
A one liner suggested by Matthias
print(('No', 'Yes')[sum(i for i inrange(1, n) ifnot n % i) == n])
Solution 2:
There is a cool one liner in comment section of this answer
other have already pointed out your mistake so here is how you can optimize your code a little bit.
greatest divisor of 6( =n)
other than 6 is 3( = n//2)
since we don't add number itself to factors_sum
while checking whether sum of factors equals to number( ie while finding perfect number),so we don't need to check whether any number greater than 3
is a factor of 6 or not.
# perfect nums example 6, 28, 496, and 8,128
n = 8128
stop = (n//2) +1# stop is exclusive thats why extra 1
factors_sum = 0for i inrange(1,stop):
if n % i == 0:
factors_sum += i
print('Yes'if factors_sum == n else'No') # Yes'''
benchmark result( using timeit ran each five times)
for smaller value of n there is no significant difference but as the value of n becomes very large you can clear see the difference.
n = 33550336
1) stop = (n//2) +1
6.580396663 ( time in secs)
2) stop = n
12.635774489000001 ( time in secs)
'''
Post a Comment for "Why Is My Code Displaying The Wrong Output?"