我想计算二进制搜索找到正确项所需的递归次数(100(。我实现了这个Counter类,我认为它不起作用,但我尝试了一下。我原以为我会重新设置(或者"覆盖"(以前的实例化,但事实似乎并非如此,因为计数器似乎可以工作。
我有三个问题:
- 有没有更好的方法来实现这个特定搜索案例的计数器
- 为什么在每次递归发生时都不覆盖以前的实例化
- 当我说";递归发生">
from dataclasses import dataclass
@dataclass
class Counter:
c = 0
def binary_search(container, item, left, right):
count = Counter
count.c +=1
print("count: ", count.c)
# first base case - search misses
if right < left:
return -1
# generate the index of the middle item
middle_index = (left + right) // 2
# we have found the item
if container[middle_index] == item:
return middle_index
# have to check whether the middle_item is smaller or greater
# the item is in the left subèarray
elif container[middle_index] > item:
print('Checking items on the left. . .')
# we can discard the right side of the array (items greater than the middle item)
return binary_search(container, item, left, middle_index-1)
elif container[middle_index] < item:
print('Checking items on the right. . .')
return binary_search(container, item, middle_index+1, right)
nums = [-5,-4,0,2,4,6,8,100,500]
print(binary_search(nums, 100,0 ,len(nums)-1))
结果:
count: 1
Checking items on the right. . .
count: 2
Checking items on the right. . .
count: 3
7
谢谢
关于问题2:您不是在创建类Counter
的实例,而是引用类本身:
count = Counter
count.c +=1
这意味着,count.c
始终是相同的变量。如果你写
count = Counter()
count.c +=1
则CCD_ 3总是一个"新鲜"变量。