Skip to content

Instantly share code, notes, and snippets.

@oldsharp
Last active March 24, 2017 12:18
Show Gist options
  • Save oldsharp/919649336a3de54fb28dba0d52d4a445 to your computer and use it in GitHub Desktop.
Save oldsharp/919649336a3de54fb28dba0d52d4a445 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Author: Ray Chen <oldsharp@gmail.com>
# License: Public domain
import sys
TABLE = [
'0', # 0
'1', # 1
"abc", # 2
"def", # 3
"ghi", # 4
"jkl", # 5
"mno", # 6
"pqrs", # 7
"tuv", # 8
"wxyz" # 9
]
def f(user_input):
"""Main routine."""
# This gives a initial pos array: [0, 0, 0, ..., 0].
pos_array = [0] * len(user_input)
while True:
# Get the pos array to be printed this round.
for i, char in enumerate(user_input):
if pos_array[i] == len(TABLE[int(char)]):
if i + 1 == len(user_input):
# Finished
return
else:
pos_array[i+1] += 1
pos_array[i] = 0
# Print the str this round.
for i, char in enumerate(user_input):
sys.stdout.write(TABLE[int(char)][pos_array[i]])
sys.stdout.write('\n')
pos_array[0] += 1
if __name__ == "__main__":
while True:
try:
f(raw_input("--> "))
except EOFError:
print "Bye"
break
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Author: Ray Chen <oldsharp@gmail.com>
# License: Public domain
import sys
TABLE = [
'0', # 0
'1', # 1
"abc", # 2
"def", # 3
"ghi", # 4
"jkl", # 5
"mno", # 6
"pqrs", # 7
"tuv", # 8
"wxyz" # 9
]
def echo(pos_array, user_input):
"""Write chars to stdout according current pos state."""
for i, char in enumerate(user_input):
sys.stdout.write(TABLE[int(char)][pos_array[i]])
sys.stdout.write('\n')
def dfs(pos_array, user_input):
"""Do the tail recursion."""
# First we print this round's string out.
echo(pos_array, user_input)
# Now update the state.
pos_array[0] += 1
for i, char in enumerate(user_input):
if pos_array[i] == len(TABLE[int(char)]):
if i + 1 == len(user_input):
# Finished.
return
else:
pos_array[i] = 0
pos_array[i+1] += 1
# Do the recursive iteration.
dfs(pos_array, user_input)
if __name__ == "__main__":
while True:
try:
user_input = raw_input("--> ")
dfs([0]*len(user_input), user_input)
except EOFError:
print "Bye"
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment