简体   繁体   中英

Python: how to optimize this code for better performance

I use this code to syllable a list of strings, I need to be able to speed up this code to pass some tests, any ideas to improve this code and make it faster?

def separate(word):
s = ""
L = []
voc = ['a','e','i','o','u','y','j']
for letter in word:
    if len(s) < 1:
        s += letter

    elif s[len(s) - 1] not in voc:
            s += letter
    elif s.startswith('aeiouyj'):
           s +=letter

    elif letter in voc:
                s += letter
    else:
        L.append(s)
        s = letter
L.append(s)
return L

Did some small misc adjustments.

def separate(word):
    s=''
    L = []
    for letter in word:
        if s=='':
           s = letter
        elif s[-1] not in 'aeiouyj' or letter in 'aeiouyj':
             s += letter
        else:
            L.append(s)
            s = letter
    L.append(s)
    return L   

Not sure if s.startswith('aeiouyj') is of any use in original code because it never going to be True .

def separate(word):
    s = ""
    L = []
    voc = ['a','e','i','o','u','y','j']
    s=word[0]
    for letter in word[1:]:
        if s[len(s) - 1] not in voc:
            s += letter
        elif letter in voc or s.startswith('aeiouyj'):
           s +=letter
        else:
            L.append(s)
            s = letter
    L.append(s)
    return L

After analysing the code, we can see that it is going into first if just in the beginning. So, we can skip this part. One more thing you can do bring the if before last else to the second place. After analysing a Harry Potter paragraph with this program it enters into loops "1,2436,0,98,959" times respectively. The third if maybe eliminated too, since it never entered into this branch in my case.

Instead of using loops you can use recursion which is faster than it. Also Functional programming is always preferred as it is based on input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM