-2

I'm trying to make an easy dummy thing but I kinda stopped at something i never encounter. Making some kind of translator which should work like this:

word = "hello"

h => i (+1 position in alphabet)
e => g (+2)
l => o (+3)
l => p (+4)
o => t (+5)

but I (obviously) hit the end of the list at some point. Is there some kind of function(maybe) to loop the list?

To work it like this:

word = "maze"

m = n (+1)
a = c (+2)
z = c (+3 - loop thru the list to the start)
e = i (+4)

I was thinking of using -26 as the indexerror exception, but I'm kinda hoping there is going to be more beautiful posibility. Or maybe even easier solution overall?

Thanks!

Code:

import string

alphabet_list = []

word = "hello my friend"
x = 0

for char in string.ascii_lowercase:
    alphabet_list.append(char)
###     26 chars || 0 - 25     ###
# print(alphabet_list)

for character in word:
    x += 1
    if character in alphabet_list:
        print(alphabet_list[alphabet_list.index(character) + x])

Leemosh
  • 883
  • 6
  • 19
  • 1
    You're looking for the "modulo" operator - `%`. E.g. `x = (x + 1) % 26`. – Blorgbeard Aug 21 '19 at 17:07
  • Oh wow, I'm dumb. Thank you! – Leemosh Aug 21 '19 at 17:14
  • If you want to implement Caesar cipher or any (one character-to-one character) substitution cipher, I suggest taking look at str's method translate: https://www.tutorialspoint.com/python/string_translate.htm – Daweo Aug 21 '19 at 17:20
  • @Daweo I was thinking about it too but I wanted something a bit different so I added the +1 there for every character. But thanks, it might be handy :) – Leemosh Aug 21 '19 at 17:24

1 Answers1

1

Using modulo % operator. This will work for lowercase letters from a to z:

def code(s):
    a = ord('a')
    return ''.join( chr(a + ((ord(c) - a) + i) % 26) for i, c in enumerate(s, 1) )

def decode(s):
    a = ord('a')
    return ''.join( chr(a + ((ord(c) - a) - i) % 26) for i, c in enumerate(s, 1) )

coded_string = code('maze')

print(coded_string)
print(decode(coded_string))

Prints:

ncci
maze
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
  • 1
    This one is looking pretty good too, the only flaw I have here are whitespaces. But this one works well too. Thanks! – Leemosh Aug 21 '19 at 17:22