【发布时间】:2021-11-12 22:17:21
【问题描述】:
大家好,我正在解决问题我对我的第一个函数进行了很多更改以达到时间限制
但这真的是我最后的想法,我不知道如何让它比现在更快
from timeit import default_timer as timer
from datetime import timedelta
start = timer()
testList = ['hello']
wordList = ['hello','helloetttttttttttttttttttttttttwersdfffffffffffffffffffffffffffffffavvvvvvvvvvvvvvvvvvvvvvvvvqwewqe','helloetttttttttttttttttttttttttwersdfffffffffffffffffffffffffffffffavvvvvvvvvvvvvvvvvvvvvvvvvqwewqe','helloetttttttttttttttttttttttttwersdfffffffffffffffffffffffffffffffavvvvvvvvvvvvvvvvvvvvvvvvvqwewqe','helloetttttttttttttttttttttttttwersdfffffffffffffffffffffffffffffffavvvvvvvvvvvvvvvvvvvvvvvvvqwewqe','helloetttttttttttttttttttttttttwersdfffffffffffffffffffffffffffffffavvvvvvvvvvvvvvvvvvvvvvvvvqwewqe']
def words_with_given_shape(words,shape):
itemList = 'abcdefghijklmnopqrstuvwxyz'
def wordShape(word):
tempS = []
termil = len(word)-1
for inx,elem in enumerate(word):
orderAl = itemList.index(elem)
if inx < termil:
orderNl = itemList.find(word[inx+1])
if orderAl > orderNl:
tempS.append(-1)
if orderAl < orderNl:
tempS.append(1)
if orderNl == orderAl:
tempS.append(0)
return tempS
def checkWord(words):
res = []
for i in words:
if wordShape(i)==shape:
res.append(i)
return res
return checkWord(words)
print(words_with_given_shape(wordList, [-1, 1, 0, 1,1,1,-1]))
print(words_with_given_shape(wordList, [-1, 1, 0, 1]))
print(words_with_given_shape(wordList, [-1, 1]))
print(words_with_given_shape(wordList, [-1, 1, 0, 1,1, 0, 1,-1,1]))
print(words_with_given_shape(testList, [-1, 1, 0, 1]))
end = timer()
print(timedelta(seconds=end-start))
这次它给了我 0:00:00.001272
但似乎测试人员需要比这更快,因为在测试 12 时由于执行时间限制而失败
那么基本上你能指导我使 words_with_given_shape 函数更加优化吗?
*** 编辑***: 我忘了说问题是它给出了单词列表和单词的形状 形状就像 [0,1,1,-1] 这意味着 0当量 1 个字符在当前字符之后,按字母顺序排列 -1 个字符在当前字符之前,按字母顺序排列
所以你好 它的 [-1, 1, 0, 1]
答案是找到单词列表中所有形状与形状 arg 相同的单词
【问题讨论】:
-
测试人员在哪里?
-
不是为每个单词生成形状,只需对照单词检查现有形状;这样你就可以尽早失败。另外,首先按长度过滤单词列表。
标签: python python-3.x optimization code-organization