Skip to content

Instantly share code, notes, and snippets.

@stormmore
Created December 3, 2017 23:54
Show Gist options
  • Save stormmore/2469974c6b2af80f04581e685d780119 to your computer and use it in GitHub Desktop.
Save stormmore/2469974c6b2af80f04581e685d780119 to your computer and use it in GitHub Desktop.
Convert words to commands
def wordToCommands(word, cols):
''' ASCII code for A '''
orda = ord('A')
'''
Starting POS (equivalent of A)
(tuple):
first position represents up / down
second postion left / right
'''
currentPos = (0,0)
''' Initialize list of commands '''
commands = []
''' Make all characters uppercase '''
word = word.upper()
for ch in word:
''' Calculate ch's numeric value '''
ch = ord(ch) - orda
''' Calculate ch's grid position '''
newPos = (ch // cols, ch % cols)
''' Calculate number of moves to get to ch's position '''
moves = (newPos[0] - currentPos[0], newPos[1] - currentPos[1])
if moves[0] < 0:
commands += ['U'] * -moves[0]
elif moves[0] > 0:
commands += ['D'] * moves[0]
if moves[1] < 0:
commands += ['L'] * -moves[1]
elif moves[1] > 0:
commands += ['R'] * moves[1]
if commands:
commands += ['E']
currentPos = newPos
return ','.join(commands)
print(wordToCommands('cars', 5))
print(wordToCommands('help', 5))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment