Bit by bit

I wrote the following code to transform a series of comma separated numbers to alternating zeros and ones e.g. 4,3,4,3 is 00001110000111.

line = "4,3,4,3"
x=[]
bit = 0
start = 0
for series in line.split(","):
  for i in range(int(series)):
    x.append(bit)
    #proceed to next value
    bit = (bit + 1) % 2
  start += int(series)
print("".join([str(i) for i in x]))

But it could be so much better like so:

chars = ["0","1"]
line = "4,3,4,3"
chars = ["0","1"]
x = [chars[i%2]*int(x) for (i,x) in enumerate(line.split(","))]
print("".join(x))

My insight is that when the code goes bit by bit or character by character there must be a better way.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s