大佬教程收集整理的这篇文章主要介绍了Python中类中声明的全局变量,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一段时间想退出这个问题,并想确保我正确理解它。我现在正在研究一个关于算法的问题
流中的第 K 个最大数
设计一个类来有效地找到数字流中第 K 个最大的元素。
这个类应该有以下两件事:
结果是:
from heapq import *
class KthLargestnumberinstream:
# minHeap = []
def __init__(self,_input,_k):
self.k = _k
# the update minHeap will keep in the class and won't get cleared
self.minHeap = []
# rather than assigning values to input
# call the add function to add
for num in _input:
self.add(num)
def add(self,num):
# minHeap is defined outsIDe this function and within the class
# need to use the self.minHeap to call it
heappush(self.minHeap,num)
# return the top k
if len(self.minHeap) > self.k:
heappop(self.minHeap)
# print(self.minHeap)
return self.minHeap[0]
def main():
kthLargestnumber = KthLargestnumberinstream([3,1,5,12,2,11],4)
print("4th largest number is: " + str(kthLargestnumber.add(6)))
print("4th largest number is: " + str(kthLargestnumber.add(13)))
print("4th largest number is: " + str(kthLargestnumber.add(4)))
main()
打印出最小堆中访问过的所有元素如下:
[3]
[1,3]
[1,3,5]
[1,12]
[1,11]
[1,11,6]
4th largest number is: 1
[1,6,13]
4th largest number is: 1
[1,4,13,12]
4th largest number is: 1
我很好奇每次我们调用 kthLargestnumber = KthLargestnumberinstream([3,4)
时,为什么它不会创建@R_618_10062@空堆,然后向其中添加值,而是保留之前调用 add
时的元素}} 函数。
然而,在这个问题 Anther question 中,@H_411_16@max_sum 每次都会被重置。
提前感谢您的帮助。
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)
以上是大佬教程为你收集整理的Python中类中声明的全局变量全部内容,希望文章能够帮你解决Python中类中声明的全局变量所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。