0

I did read related answers, but still can't figure out how to do my list comprehension properly.

I wrote functions to convert binary to decimal and other way around, but in my decimal to binary conversion I wanted to use list comprehension instead of cycles that I'm using now, yet I can't figure out how to write it correctly.

My code is as follows:

from math import log

def dec_to_binary(n: int) -> str:
    """Convert integer to binary."""
    indices = []
    
    while n > 0:
        index = int(log(n, 2))
        indices.append(index)
        n -= 2**index
    binary = ['0' for x in range(max(indices)+1)]
    
    for i in indices:
        binary[i] = '1'
        
    binary = binary[::-1]
    binary = ''.join(binary)
    return binary

Here I'm repeatedly calculating a log(2) of a number to get indices which will become 1s in the final binary number. After that I create a list of zeroes with length equal to the highest log value and then replace '0' with '1' in corresponding indices.

This works fine, but I was trying to see if I could do it all in one go, but what I came up with so far doesn't seem to work:

binary = ['0' for x in range(max(indices)+1) if x not in indices else '1']

Interpreter keeps pointing to error at the else statement.

binary = ['0' for x in range(max(indices)+1) if x not in indices else '1']
  File "<ipython-input-297-3da1307fffd5>", line 1
    binary = ['0' for x in range(max(indices)+1) if x not in indices else '1']
                                                                      ^
SyntaxError: invalid syntax

How can I re-write it correctly?

NotAName
  • 3,821
  • 2
  • 29
  • 44

1 Answers1

2

Put the if/else at the front

binary = ['0' if x not in indices else '1' for x in range(max(indices)+1)]
drum
  • 5,416
  • 7
  • 57
  • 91