+ 4

Fisher number code does not work for 24

This code seems to work in general with all numbers, but not with 24! It recognise 24 as a Fisher number, which is not true. With this number the code counts i to 12 instead to 24. Could somebody explain this or find the error? _____ n = int(input()) beans = 1 ham = 0 spam = list(filter(lambda i: (n % i == 0), list(range(2,n+1)))) eggs = ' x '.join([str(x) for x in spam]) for i in spam: beans *= i if n**3 == beans: print(spam, "==", i, "\n", eggs, "\n", beans) print(n, "is a Fisher number, because", str(n)+"^3 = "+eggs+".") ham = 1 if not ham: print(n, "is not a Fisher number.") _____

12th Sep 2018, 11:59 AM
blackfish
blackfish - avatar
3 Réponses
+ 2
blackfish your if statement after beans*=i is not a right place because it is check every turn and you need to check this if statement when your for loop complete.and renamed if into elif in last statement. now it give you right output. check this code i modify your code. n = int(input()) beans = 1 ham = 0 spam = list(filter(lambda i: (n % i == 0), list(range(2,n+1)))) eggs = ' x '.join([str(x) for x in spam]) for i in spam: beans *= i if n**3 == beans: print(spam, "==", i, "\n", eggs, "\n", beans) print(n, "is a Fisher number, because", str(n)+"^3 = "+eggs+".") ham = 1 elif not ham: print(n, "is not a Fisher number.")
12th Sep 2018, 4:03 PM
Maninder $ingh
Maninder $ingh - avatar
+ 2
blackfish every time when beans*=i run then after run if statement means if product of the numbers is equal to the n**3 then it will be True although some number remain to multiply with beans then there is logic error. 2×3×4×6×8 is when multiply then it will be equal to n**3 and then if statement run which execute True but 24 is remain multiple with beans so we can say we only need to check if statement when all the multiply with beans.
12th Sep 2018, 5:50 PM
Maninder $ingh
Maninder $ingh - avatar
+ 1
Maninder Singh Thank you. But does it mean, that "for... beans*=i" is an independent calculation (similar to "spam" and "eggs"), not a part of the following if-statement, isn't it?
12th Sep 2018, 4:52 PM
blackfish
blackfish - avatar