简体   繁体   English

Python:如何优化此代码以获得更好的性能

[英]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 .不确定s.startswith('aeiouyj')在原始代码中是否有用,因为它永远不会是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.您还可以做的另一件事是将 if before last else 排在第二位。 After analysing a Harry Potter paragraph with this program it enters into loops "1,2436,0,98,959" times respectively.用这个程序分析哈利波特的一段后,它分别进入循环“1,2436,0,98,959”次。 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.此外,函数式编程始终是首选,因为它基于输入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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