'Why does this counter (class instance) work properly and doesn't re-initialize at every recursion occurrence? (Python 3.8)
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:
- Is there a better way to implement a counter for this specific search case?
- Why is the previous instantiation not overwritten at each recursion occurrence?
- Am I using the right vocabulary when I say "recursion occurrence"?
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
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dirk Herrmann |
