Skip to content Skip to sidebar Skip to footer

Python String And Lists

Been sitting on this minor problem a few days now, I don't know if I have it all wrong or just missed out on something. The Objective: From each word in a sentence - Find the firs

Solution 1:

How about something like this:

import re

def bebis_word(word):
    first_vowel = re.search("[aeiou]", word, re.IGNORECASE)

    if first_vowel:
        return word[0:first_vowel.start() + 1] * 3
    else:
        return ''    

def bebis(sentence):
    words = [bebis_word(word) for word in sentence.split()]

    return " ".join(words)

print bebis("Hello World")

Output:

HeHeHe WoWoWo


Solution 2:

Your approach seems correct (splitting the sentence into words and iterating on the words to find the first vowel).

The problem is that your tkn1 variable is a letter, so len(tkn1) is always 1, so count=1

Here's a potential solution:

def bebis(inrad):
    utrad = ""
    inrad = inrad.split()
    # Loop on words 
    for tkn in inrad:
        # Loop on letters in the word
        for (i,tkn1) in enumerate(tkn): #Eftersom tkn ar ordlista nu.
            if tkn1 in vokaler:
                utrad += tkn[:i+1] * 3
                break
        utrad += " "
    return utrad

Here, we use the enumerate function that will give a list of tuples (index,letter). Once we tested that the current letter is a vowel, we take the first letters of the word (tkn[:i+1]), repeat them three times, store them in utrad and move to the next word (with the break statement that leaves the current loop). We just have to add an extra space between words.


Solution 3:

Just as an alternative to the regular expression approach, I did:

def find_vowel_index(word):
    vows = set(["a", "e", "i", "o", "u"])
    for i, letter in enumerate(word):
            if letter in vows:
                    return i
    return -1 

def bebis(s, repeat=3):
    return " ".join([word[0:find_vowel_index(word)+1] * repeat for word in s.split() if find_vowel_index(word) >= 0])

Thoughts:

  • I did a set for the vowels as the "in" test on a set is a constant time operation (O(1))
  • added an optional repeat argument to bebis, so that if you want the word to repeat some number of times other than 3 it's easy to do so.
  • I don't like the multiple calls to find_vowel_index in bebis, it could be structured better.
  • a trade-off over the regex version is that this will get slower as words get longer (and have vowels "deeper" in the word). OTOH, I'd guess that on short words the overhead of the regex might be a bit costly.

Post a Comment for "Python String And Lists"