2 回答
TA贡献1805条经验 获得超9个赞
我看到有一个答案可以解决您的错误消息,但我想提供一些建议来改进您的代码。
这f1()是您的代码,f2()是我改进的建议;它的代码更少,在我看来更容易理解,运行时间也更少。
def f1(inputString):
inputStringArray = list(inputString) # break into char arrray
letterArray = []
posY = 28
for i in range(26): # create balnk list of 0s of size 26x26
letterArray.append([])
for j in range(26):
letterArray[i].append(0)
for letter in inputStringArray:
posX = ord(letter)-97 # -97 so that a = 0, z = 25
if posY is 28 and posX <= 26 and posX >= 0: # instantiate first instance of past letter
posY = posX
continue
if posX <= 26 and posX >= 0: # if the char is a letter
x = letterArray[posY][posX]
x +=1
letterArray[posY][posX] = x # increment the space in the array by 1
posY = posX
else:
continue
return letterArray
def f2(input_str):
max_n = 26
# build nested lists with zeros
letter_list = [
[0, ] * max_n
for _ in range(max_n)]
# 'None' is usually used to indicate an invalid value
prev_i = None
for letter in input_str:
curr_i = ord(letter) - 97
if 0 <= curr_i <= max_n:
if prev_i is not None:
letter_list[prev_i][curr_i] += 1
prev_i = curr_i
return letter_list
断言结果相同:
>>> s = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat'
>>> r1 = f1(s)
>>> r2 = f2(s)
>>> r1 == r2
True
比较运行时(此示例输入f2需要一半的时间f1):
>>> import timeit
>>> timeit.timeit('f1(s)', 'from __main__ import f1, s', number=10000)
1.0122240540222265
>>> timeit.timeit('f2(s)', 'from __main__ import f2, s', number=10000)
0.4270052219508216
添加回答
举报