我正在编写一段代码,它遍历一个链表,搜索给定的值列表,并返回它的位置。这是代码:
def bruteForce(aList, data):
index = 0
curr = aList.getHead()
while(curr.getNext() != None):
if(curr.getData() == data[0]):
match = 0
for i in range(len(data)):
if(curr.getData() == data[i]):
match += 1
if(match == len(data)):
print("Found a match at " + str(index) + "!")
curr = curr.getNext()
index += 1
curr = curr.getNext()
index += 1
我这样称呼它:
file11 = input("What are we searching for today in file 1? ")
file12 = input("What else are we searching for today in file 1? ")
print("Now searching using Brute Force!")
startBF = time.time()
bruteForce(ickleList, file11)
bruteForce(ickleList, file12)
endBF = time.time()
bruteForceTime = endBF - startBF
我得到错误:
Traceback (most recent call last):
File "Find It Fast.py", line 251, in <module>
bruteForce(ickleList, file12)
File "Find It Fast.py", line 147, in bruteForce
if(curr.getData() == data[i]):
AttributeError: 'NoneType' object has no attribute 'getData'
我的while
循环检查以捕获None
类型,但它没有捕获这个类型,尽管它在第一次调用中捕获了它。
我该如何防止这种情况发生?
错误由最内部的curr = curr.getNext()
触发。您在循环中执行这些调用,但从不检查curr
是否为None
,即您是否到达了列表的末尾。在外部循环中执行检查,但在内部循环的迭代过程中不进行检查。
无论如何,即使你纠正了这种情况,这个算法也不会是防弹的。
假设您搜索";a"b"c";在一个列表中;a"a"b"c";。此代码(当您的问题得到纠正时(将找不到匹配项,因为它将集中在第一个";a";,并且内环将CCD_ 6向前移动三个位置。但当时它已经错过了良好的比赛起点,根本找不到比赛。
在失败的匹配之后,暴力算法必须返回开始尝试的位置,然后在主循环中继续。
此外,一旦发现不匹配,就应该立即退出对数据的迭代。在那一刻,你已经知道了结果,继续内部循环不会改变这一点。
这里是修复:
def bruteForce(aList, data):
index = 0
curr = aList.getHead()
while curr.getNext() != None:
temp = curr # Use another reference for comparing with data
for value in data: # Get data values directly
# Avoid error and check the list still has a node here
if temp is None or temp.getData() != value:
break # Mismatch: No need to look further.
temp = temp.getNext() # Don't move curr here
else: # when all of data matches
return index # Success!
# ... continue with the original reference
curr = curr.getNext()
index += 1
return -1 # Indication that there was no match
我不会在函数中打印任何内容。让这个函数的调用者决定要做什么:
- 返回值是-1?然后报告没有匹配
- 返回值为>0?然后报告这个值:它是找到匹配项的索引