Reputation: 359
I have a problem with this code:
num = 111
num_list = list(map(int, str(num)))
i=len(num_list)
t=2**(i-1)
answer = sum([x*(l**2) for x in reversed(num_list) for l in range(len(num_list))])
if answer % 5 == 0:
print(answer, "is divisible by 5")
else:
print(answer, "is not divisible by five")
Yes it does work if you test it but it gives me :
15 is divisible by 5
instead of:
7 is not divisible by 5
So basically what my code does is it takes a binary number and turns into decimal and tests whether or not the decimal is divisible by 5. Don't ask me how but I know there is some problem with my list comphrehension and my double for loop. Please help and thank you!
Upvotes: 1
Views: 215
Reputation: 152
You could also do this as well:
num = 111
num_list = list(map(int, str(num)))
i=len(num_list)
t=2**(i-1)
answer = 0
for l in num_list:
answer += l*t
t=int(t/2)
if answer % 5 == 0:
print(answer, "is divisible by 5")
else:
print(answer, "is not divisible by five")
Upvotes: 2
Reputation: 23146
Your logic for converting binary to decimal is a bit off. Try this:
answer = sum([x*(2**l) for l, x in enumerate(reversed(num_list))])
>>> answer
7
Upvotes: 4