I’m working on a simple python script that takes a number, converts it to binary, and returns the sum of the binary digits. Here is what I have so far.
#!/usr/bin/python
def sum2(n):
a = str(bin(n))
b = a.replace('0b', '')
return sum([map(int, x) for x in b])
n = int(raw_input("Input number>"))
print sum2(n)
In plain English I take n and convert it to binary, and then convert it to a string. I chop off the 0b (from bin()) and convert the binary characters into a list of ints and then attempt to sum() them.
When trying to figure out how to add the digits together I googled around and found that I should be able to sum() a list of ints. When I attempt to do this, I end up with this traceback.
Traceback (most recent call last):
File "D:\scripts\sum2n1.py", line 9, in <module>
print sum2(x)
File "D:\scripts\sum2n1.py", line 6, in sum2
return sum([map(int, x) for x in b])
TypeError: unsupported operand type(s) for +: 'int' and 'list'
So I find out sum() needs an “iterable” to do it’s job. I google around and find there’s an iter() function I can call, but it doesn’t seem to work.
There's also __iter__() which doesn't work either.
Can anyone tell me what I’m doing wrong? I’m still quite a bit of a beginner. Thanks in advance.
(And no, it’s not my homework.)
You are combining list comprehensions with the
mapfunction, in an apparent attempt to do the same thing twice. You want either:or