I am coding in Python 2.7 using PyCharm on Ubuntu.
I am trying to create a function that will take a string and change each character to the character that would be
This can be done much easier and efficiently by using a look-up instead of using index
for each letter.
look_up = dict(zip(string.ascii_lowercase, string.ascii_lowercase[1:]+'a'))
The zip above creates tuples of the form ('a', 'b')...
including ('z', 'a')
. Feeding that into the dict constructor makes a dict of the same form.
So now the code can be simply:
def LetterChanges(s):
from string import ascii_lowercase
look_up = dict(zip(ascii_lowercase, ascii_lowercase[1:]+'a'))
new_s = ''
for letter in s:
new_s += look_up[letter]
return new_s
Even this dict creation and the loop can be saved by using the str.maketrans method and feeding its result to str.translate:
def LetterChanges(s):
from string import ascii_lowercase
return s.translate(str.maketrans(ascii_lowercase, ascii_lowercase[1:]+'a'))
this is my code i think it is very simple
def LetterChanges(st):
index = 0
new_word = ""
alphapet = "abcdefghijklmnopqrstuvwxyzacd"
for i in st.lower():
if i.islower(): #check if i s letter
index = alphapet.index(i) + 1 #get the index of the following letter
new_word += alphapet[index]
else: #if not letter
new_word += i
return new_word
print LetterChanges(raw_input())