繁体   English   中英

为什么这个计数器(类实例)可以正常工作并且不会在每次递归发生时重新初始化? (蟒蛇 3.8)

[英]Why does this counter (class instance) work properly and doesn't re-initialize at every recursion occurrence? (Python 3.8)

我想计算二分搜索找到正确项所需的递归次数 (100)。 我实现了这个计数器 class,我认为它不会工作,但我尝试了一下作为实验。 我以为我会重新设置(或“覆盖”)以前的实例化,但情况似乎并非如此,因为计数器似乎在工作。

我在这里有三个问题:

  1. 有没有更好的方法来为这个特定的搜索案例实现一个计数器?
  2. 为什么在每次递归发生时不覆盖先前的实例化?
  3. 当我说“递归发生”时,我是否使用了正确的词汇?
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:您没有创建 class Counter的实例,而是引用 class 本身:

count = Counter
count.c +=1

这意味着, count.c始终是同一个变量。 相反,如果你写

count = Counter()
count.c +=1

那么count.c始终是一个“新鲜”变量。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM