Home > Blockchain >  Can someone please break this code down and explain it?
Can someone please break this code down and explain it?

Time:10-28

The problem is: Given an array of numbers, check if any of the numbers are the character codes for lower case vowels (a, e, i, o, u).

Here is where I am curious...

This:

def is_vow(inp):
    for key, val in enumerate(inp):
        if chr(val) in 'aeiou':
            inp[key] = chr(val)
    return inp

Does the same thing as this: (Which is what I wrote)

def is_vow(inp):
    lst1 = []
    for vow in inp:
        if vow == 97:
            lst1.append('a')
        elif vow == 101:
            lst1.append('e')
        elif vow == 105:
            lst1.append('i')
        elif vow == 111:
            lst1.append('o')
        elif vow == 117:
            lst1.append('u')
        else:
            lst1.append(vow)
    return lst1

I get that the first solution will enumerate through the parameter 'inp' and checks to see if the character is in 'aeiou', I just don't get how it returns the correct values...

I just want to understand it so I can learn how to shorten my code and not have to repeat myself.

P.S. - I'm still new to the Python language.

CodePudding user response:

inp = [97, 99, ...]
for i, val in enumerate(inp):

Step through the input list, keeping an index (I renamed i).

if chr(val) in 'aeiou':

Parse the number as ascii (chr()) and then see if it's one of aeiou. Remember strings are iterable in python. (chr() is the magic here you probably didn't expect; try it out in a repl).

inp[i] = chr(val)

Replace the current element in the original list with it's ascii equivalent. Notice that we call chr twice! This would be more efficient:

c = chr(val)
if c in "aeiou":
    inp[i] = c

You can also write that with the dreaded walrus operator, but I leave that as an exercise for the reader ;)

  • Related