Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replacing the Alphabet with a Numerical Value

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

"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.

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading