1

This is a challenge from Kata. The function should return the max amount of subsequent vowels in a string.

I found this really practical solution after completing it myself.

Can someone explain the code step by step? I would like to thoroughly understand how the join and split bits complete each other here.

def solve(string):
    return max(map(len, ''.join(i if i in 'aeiou' else ' ' for i in string).split()))
yatu
  • 75,195
  • 11
  • 47
  • 89
coding girl
  • 109
  • 11
  • Although not an answer. The code provided is indeed not easily understandable. I would personally go for a multiline `max(map(len, re.findall(r'[aeiou]+', string)))` – 3limin4t0r Sep 19 '19 at 13:36

1 Answers1

5

The best thing to do in these cases is to simplify and divide into smaller parts. The join is simply joining together a sequence of strings composed by either a vowel or an empty space from the conditional generator comprehension:

s = 'aei234roieeieigfh'

out1 = ''.join(i if i in 'aeiou' else ' ' for i in s)
# 'aei    oieeiei   '

The above is just a fancy way of writting the following generator function:

def f(s):
    for i in s:
        if i in 'aeiou':
            yield i
        else:
            yield ' '

''.join(f(s))
# 'aei    oieeiei   '

Then by splitting you get a list of strings as:

out2 = out1.split()
# ['aei', 'oieeiei']

Then by mapping with the len, you're taking the len of each item in the list:

list(map(len, out2))
# [3, 7]

Which is the same as doing:

[len(i) for i in out2]
# [3, 7]

And finally by taking the max you'll find the longest sequence of vowels in the list.


I personally would go with itertools.groupby here :)

max(len(list(v)) for k,v in groupby(s, key=lambda x: x in 'aeiou') if k)
# 7

Some reads you might find useful:

yatu
  • 75,195
  • 11
  • 47
  • 89