Importing groupie

The following code transforms a string of zeros and ones in a form of consecutive zeros and ones. E.g., “00001110000111” will be 4,3,4,3.

from itertools import groupby

groups = groupby(row)
text=",".join([str(len(list(appearances)))
for (_,appearances) in groups])

Without importing I had written the following code for the same task:

nums = []
count = 0
countType = 0 #0 means white
#1 means black
for cell in row:
  if int(cell) == countType:
     count+=1
  else:
    nums.append(count)
    countType = (countType + 1) % 2
  count = 1
  nums.append(count)
text = ",".join([str(x) for x in nums])

For a minute I thought that the original code was more readable than the groupby one but I was wrong.

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