Skip to content

Instantly share code, notes, and snippets.

@damiankao
Last active December 12, 2015 12:29
Show Gist options
  • Save damiankao/908fe1fd6562dc75f40c to your computer and use it in GitHub Desktop.
Save damiankao/908fe1fd6562dc75f40c to your computer and use it in GitHub Desktop.
Simple implementation of Burrows-Wheeler transformation in python
def encode(inputStr):
rotations = [inputStr[i:] + inputStr[:i] for i in range(len(inputStr))]
rotations.sort()
encodedStr = [x[-1] for x in rotations]
index = rotations.index(inputStr)
return (''.join(encodedStr), index)
def decode(encodedStr, index):
rotations = [encodedStr[i] for i in range(len(encodedStr))]
for i in range(len(encodedStr) - 1):
rotations.sort(key = lambda x : x[0])
rotations = [encodedStr[i] + x for i,x in enumerate(rotations)]
rotations.sort(key = lambda x : x[0])
return rotations[index]
encode('damiankao') #outputs 'dikomnaaa' and 3
decode('dikomnaaa',3) #outputs 'damiankao'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment