这是 A-Level 计算机科学课程中一系列问题的结果。
任务是修改现有的、写得不好的程序来完成多项任务。
此任务的任务是修改程序,通过更改
linearSearch
和 binarySearch
来比较每次搜索的时间效率,以返回一个计数变量,每次进行比较时该变量都会加一。然后创建一个函数,对不同长度的列表进行一系列测试,并输出每个列表的平均比较次数。
下面代码的问题是一个逻辑错误,导致每组的平均值“完全相同”。我尝试过修改变量标识符,但没有帮助。
def linearSearch(searchList, searchVal):
count = 0
for i in range(0,len(searchList)):
count += 1
if searchList[i] == searchVal:
return i
return count
def binarySearch(searchList, searchVal):
start = 0
count = 0
end = len(searchList) - 1
while start <= end:
mid = (start + end) // 2
count += 1
if searchList[mid] == searchVal:
return mid
elif searchList[mid] < searchVal:
start = mid + 1
elif searchList[mid] > searchVal:
end = mid - 1
return count
def generateList(limit):
list = []
for i in range(limit):
list.append(i)
return list
import random
def test():
testType = 1
while testType <= 5:
linearTestNo = 0
binaryTestNo = 0
length = 10**testType
searchList = generateList(length)
linearCountTotal = 0
binaryCountTotal = 0
while linearTestNo <= 100 and binaryTestNo <= 100:
x = random.randint(0,length-1)
linearCountTotal += linearSearch(searchList, x)
linearTestNo += 1
binaryCountTotal += binarySearch(searchList, x)
binaryTestNo += 1
print(f"Linear Search took {linearCountTotal/100} comparisons on average for a list of {length} items")
print(f"Binary Search took {binaryCountTotal/100} comparisons on average for a list of {length} items")
testType += 1
test()
根据老师的建议,我将
TestNo
变量拆分为每个变量,尽管这不会改变任何内容。我这样做了,但错误仍然发生。