I wanted to count the number of recursion occurrence my binary search would require to find the right item (100). I implemented this Counter class, I thought that it wouldn't work but I gave it a try as an experiment. I thought that I would re-set so to speak (or "overwrite") the previous instantiation, but it doesn't seem to be the case as the counter seem to work.
I have three questions here:
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))
Result:
count: 1
Checking items on the right. . .
count: 2
Checking items on the right. . .
count: 3
7
Thank you
Regarding your question 2: You are not creating an instance of class Counter
, but instead refer to the class itself:
count = Counter
count.c +=1
This means, count.c
is always the same variable. If instead you write
count = Counter()
count.c +=1
then count.c
is always a 'fresh' variable.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.