I am trying to solve this challenge, but my code doesn't seem to work, is there a fix? Here is the question:
In this kata you are required to, given a string, replace every letter with its position in the alphabet.
If anything in the text isn't a letter, ignore it and don't return it.
"a" = 1, "b" = 2, etc.
Example alphabet_position("The sunset sets at twelve o' clock.") Should return "20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11" ( as a string )
Here is my code:
`
def alphabet_position(text):
new= ''
a1 = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
a2 = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
n= ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26']
for i in range(0, len(text)-1):
if i in a1:
index= a1.index(i)
new = n[index]
elif i in a2:
index=a2.index(i)
new = n[index]
return new
`
CodePudding user response:
As previous posts (@John Coleman) suggested, it's easier to just use ord to solve it:
Credit to him and earlier comments.
def alphabet_position(s):
return " ".join(str(ord(c)-ord("a") 1) for c in s.lower() if c.isalpha())
# Or you still like your original mapping approach:
def alphabet_position(text):
letters = "abcdefghijklmnopqrstuvwxyz"
return " ".join([str(letters.find(c) 1)
for c in text.lower() if c in letters])
print(alphabet_position("The sunset sets at twelve o' clock."))
# 20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11
CodePudding user response:
There are 2 problems with your code:
You are comparing the numerical index of a letter with
a1
anda2
. No numerical index is a letter, so neither of yourif
branches are ever executed, which is why you always get the empty string returned. The solution is to directly iterate over the letters intext
.You aren't putting spaces between the numbers. The solution is to gather the numbers into a list and to then join them with a space delimiter.
Making these changes leads to the following code:
def alphabet_position(text):
new= []
a1 = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
a2 = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
n= ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26']
for i in text:
if i in a1:
index= a1.index(i)
new.append(n[index])
elif i in a2:
index=a2.index(i)
new.append(n[index])
return ' '.join(new)
For example
alphabet_position("The sunset sets at twelve o' clock.")
'20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11'
This answer shows how to debug your code so that it works. The answer by Daniel Hao shows a much more pythonic approach to the problem.