嘿,伙计们,我正在解决一个问题,我对我的第一个函数做了很多修改,以达到时间限制
但这真的是我的最后一个想法,我不知道如何让它比现在更快
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时,由于执行时间限制,测试失败
所以基本上你能指导我用给定的形状函数使单词更加优化吗
***编辑***: 我忘了告诉你问题是它给出了单词列表和单词的形状 形状像[0,1,1,-1],它的意思是 0均衡器 1个字符位于当前字符后面,按字母顺序排列 -1个字符在当前字符之前,按字母顺序排列
你好 它的 [-1,1,0,1]
答案是在单词列表中找到所有形状与形状arg相同的单词
******回答
感谢@Socowi
这解决了我的问题
def words_with_given_shape(words,shape):
itemList = 'abcdefghijklmnopqrstuvwxyz'
def wordShape(word):
tempS = []
termil = len(word)-1
if termil == len(shape):
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)
Added single line
if termil == len(shape):
通过如图所示重新格式化代码并使用列表理解,您在10000次迭代中加快了100毫秒:
试试这个:
它更紧凑(只有一行),并且您不需要生成每个单词的形状(在本例中这是无用的,因为您可以使用提供的形状)
相关问题 更多 >
编程相关推荐