Replacing the Alphabet with a Numerical Value

Question:

I’ve been trying to solve this problem, I’m not allowed to use libraries or modules for my solution and I am required to use loops:

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.

My solution:

string = ("Hello")

def letter_to_number(text):
    translated = ""
    for i, j in enumerate("abcdefghijklmnopqrstuvwxyz"):
        for letter in text.lower():
            if len(text) == 1:
                if letter in j:
                    translated = translated + str(i+1)
            else:
                if letter in j:
                    translated = translated + str(i+1) + " "
    return translated


print(letter_to_number(string))

This returns the correct numbers. However, it returns the string sorted in ascending order. Like so: (5, 8, 12, 12, 15)

I need it to return (8, 5, 12, 12, 15) instead.

P.S. I am still a somewhat beginner with python.

Asked By: Cynicc

||

Answers:

Notice that this is how you’re looping:

for i, j in enumerate("abcdefghijklmnopqrstuvwxyz"):
    for letter in text.lower():

This means that, for every letter inside text, you’ll continually be iterating over the letters a..z. And you’ll be starting in alphabetical order

You probably meant to have it in the opposite order:

for letter in text.lower():
    for i, j in enumerate("abcdefghijklmnopqrstuvwxyz"):

Just to give you some extra tips here, there’s no need to iterate over the letters every time. I’m going to assume you haven’t learned about dictionaries yet, but basically you can have something like this:

letters = {"a":1, "b":2, ..., "z":26}

You can think of it like a key-value mapping (a maps to 1, b maps to 2, etc).

And you can acess these values like so:

def letter_to_number(text):
    translated = ""
    letters = {"a":1, "b":2, ..., "z":26}
    for letter in text.lower():
        if letter in letters:
        translated = translated + str(letters[i]) + " "
    return translated
Answered By: TerryA

You need to enumerate the input string rather than the alphabet. You then need to check to see if the individual letters are in your alphabet. If they are then you can get the index (and add 1 given your stated base).

Code in the question suggests that the return value should be a string. A list would be better / more useful. However:

def letter_to_number(text):
    alphabet = '_abcdefghijklmnopqrstuvwxyz'
    result = ()
    for letter in text:
        if (index := alphabet.find(letter)) > 0:
            result += (index,)
    return str(result)
print(letter_to_number('hello'))

Output:

(8, 5, 12, 12, 15)
Answered By: Vlad
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.