Created
October 26, 2012 06:57
-
-
Save dtuominen/3957325 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from string import lowercase | |
from collections import defaultdict | |
from pprint import pprint | |
def coded_vals(): | |
for i, l in enumerate(lowercase): | |
yield l, i+1 | |
def make_map(code_map): | |
d = defaultdict(int) | |
for k,v in code_map: | |
d[k] += v | |
return d | |
def alpha_to_num(letters, mapping): | |
return [mapping[l] for l in letters] | |
def num_to_alpha(nums, mapping): | |
contains = [] | |
for i in xrange(len(nums)): | |
contains.append(nums[i]) | |
if i+1 < len(nums): | |
compound = ''.join(map(str, [nums[i], nums[i+1]])) | |
print compound | |
if int(compound) <= 26: | |
contains.append(compound) | |
#contains.append(''.join((map(str, [nums[i],nums[i+1]])))) | |
return contains | |
if __name__ == '__main__': | |
letters = 'hello' | |
mapping = make_map(coded_vals()) | |
nums = alpha_to_num(letters,mapping) | |
print 'original text: {}\n'.format(letters) | |
print 'coded to numbers: {}\n'.format(''.join(map(str, nums))) | |
#print 'coding back to letters: {}\n'.format(num_to_alpha(nums, mapping)) | |
alpha = num_to_alpha(nums, mapping) | |
print alpha |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment