Created
December 3, 2017 23:54
-
-
Save stormmore/2469974c6b2af80f04581e685d780119 to your computer and use it in GitHub Desktop.
Convert words to commands
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
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