有没有一种方法可以使此代码更有效,而o(n ^ 2)

时间:2019-06-11 19:32:10

标签: python-3.x performance coding-efficiency

问题是: 给定名为“ string_list”的字符串列表,其中包含:

string_list = ["darpa","da","arprpa"]

您需要创建一个名为my_list的新列表,该列表在string_list的每个单词中包含所有3个长度可能的字符串:

my_list = ['dar', 'arp', 'rpa', 'arp', 'rpr', 'prp', 'rpa']
string_list = ["darpa","da","arprpa"]
new_list = []
for word in string_list:
    if len(word) >=3:
        i=0
        for char in word:
            if len(word[i:i+3]) == 3:
                new_list.append(word[i:i+3])
                i = i+1

print(new_list)

我的问题是: 1.我以最有效的方式解决了吗? (我知道它的o(n ^ 2)) 2.对于给定的任务,哪种代码将是最高效的,也可能是最短的。 谢谢!

1 个答案:

答案 0 :(得分:0)

如果您仅使用长度为3的单词开头,则可以将其缩短并省略是否:

string_list = ["darpa","da","arprpa"]

# as list comp
k1 = [word[start:start+3] for word in string_list for start in range(len(word)-2)]

# written out
k2 = []
for word in string_list:
    lw = len(word)              
    for start in range(lw-2):  # eliminates words shorter then 3 automatically, 
                               # range(0) or less is valid but does not enter the loop
        k2.append(word[start:start+3])  # this also removes the manual counter

print(k1)         
print(k2)

输出(相同):

['dar', 'arp', 'rpa', 'arp', 'rpr', 'prp', 'rpa']