Reputation: 31
i made a function like this
def integer(n):
num = int(''.join(n))
base = 2
answer = int(num,base)
return answer
and i want to put (1, 1, 0, 0, 1, 0, 0, 0) and answer will be 200
but i got error like this
TypeError Traceback (most recent call last)
<ipython-input-70-1c8f3fd15837> in <module>
5 return answer
6
----> 7 integer((1, 1, 0, 0, 1, 0, 0, 0))
<ipython-input-70-1c8f3fd15837> in integer(n)
1 def integer(n):
----> 2 num = int(''.join(n))
3 base = 2
4 answer = int(num,base)
5 return answer
TypeError: sequence item 0: expected str instance, int found
what is wrong with my code?
Upvotes: 2
Views: 248
Reputation: 125
As @deceze mentioned, the join
method is only used for strings. If you are passing an array of ints, where each index represents one bit, you can use this:
def integerFromBitArray(arrBits):
iResult = 0
for bit in arrBits:
iResult = (iResult << 1) | bit
return iResult
Upvotes: 1
Reputation: 1047
You need a sequence of string to use join
and you can't convert a non-string to int with an explicit base.
>>> def integer(n):
... num = ''.join(str(i) for i in n)
... base = 2
... answer = int(num, base)
... return answer
...
>>> integer((1, 1, 0, 0, 1, 0, 0, 0))
200
Upvotes: 1