I was inspired by a solution in Think Python: How to Think Like a Computer Scientist. I structured mine (into two functions) according to it, and used the technique used in
rotate_letter
. It's here if you're interested.
How can I make this better in all aspects (documentation, algorithm, variable names, and etc.)? Is memoizing rotated_string
worth it?
def rotated_letter(letter, key):
"""Returns a single-letter string representing
letter rotated by key, and returns letter if
it doesn't belong to any of the English alphabet.
letter: a single-letter string.
key: an integer.
"""
if letter.isupper():
start = ord('A')
elif letter.islower():
start = ord('a')
else:
return letter
diff = ord(letter) - start
position = (diff + key) % 26 + start
return chr(position)
def rotated_string(string, key, encrypt=True):
"""Returns string rotated by key.
string: a string.
key: an integer.
encrypt: a boolean value.
"""
result = ''
memo = {}
if not encrypt:
key = -key
for character in string:
if character in memo:
# rot_cahr denotes rotated character
rot_char = memo[character]
else:
rot_char = memo.setdefault(character, rotated_letter(character, key))
result += rot_char
return result
def main():
print(rotated_string('Hello!', 3))
print(rotated_string('Khoor!', 3, encrypt=False))
if __name__ == '__main__':
main()