0

I have tried this code multiple times. But I'm always getting the output as 45, which is wrong.

a = [1, 0, 1, 1]
value = 0
a.reverse()
print(a)             #reversed list
for i in a:
    if i==1:
        for x in range(0,len(a)):
            value += pow(2,x)
    else:
        continue
print("decimal value of binary number is:",value)
2
  • 1
    value = sum([i * ((x + 1) ** 2) for x, i in enumerate(a[::-1])]) Commented May 18, 2020 at 11:36
  • Do you know the bin function? Commented May 18, 2020 at 11:44

4 Answers 4

1

You should look into bitwise operations. It'll make this more efficient and is best practice when dealing with bits. There's also more Pythonic ways to achieve this (using int(x, 2) for example.) With bitwise operations it would look like this:

for i in a:
    value |= i
    value <<= 1
value >>= 1
Sign up to request clarification or add additional context in comments.

Comments

0

Everytime you detect a 1, you add 2^3 + 2^2 + 2^1 + 2^0 = 15, and you do this 3 times which is why you get 45. You should be doing this :

a=[1,0,1,1]
value=0
a.reverse()
print(a)             #reversed list
for pos, i in enumerate(a):
    if i==1:
        value += 2**pos
    else:
        continue
print("decimal value of binary number is:",value)

Comments

0

This code will convert you the list to a decimal number.

a=[1,0,1,1]
value=0
for i, v in enumerate(a):
    value += pow(2, i) * v

print("decimal value of binary number is:",value)

Output

decimal value of binary number is: 13

Comments

0

When converting the list to a string, one can use the int function:

int("".join(map(str,a[::-1])), base=2)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.