Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
124 views
in Technique[技术] by (71.8m points)

The global variable declared in the class in Python

I have this question for quit a while and would like to make sure that I understand it correctly. I am now working on a question on algorithm

Kth Largest Number in a Stream

Design a class to efficiently find the Kth largest element in a stream of numbers.

The class should have the following two things:

  • The constructor of the class should accept an integer array containing initial numbers from the stream and an integer K.
  • The class should expose a function add(int num) which will store the given number and return the Kth largest number.

The result is:

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()

The print out the all the elements visited in the min heap is as:

[3]
[1, 3]
[1, 3, 5]
[1, 3, 5, 12]
[1, 2, 5, 12, 3]
[1, 2, 5, 12, 3, 11]
[1, 2, 5, 12, 3, 11, 6]
4th largest number is: 1
[1, 2, 5, 12, 3, 11, 6, 13]
4th largest number is: 1
[1, 2, 5, 4, 3, 11, 6, 13, 12]
4th largest number is: 1

I am curious that each time we called the kthLargestNumber = KthLargestNumberInStream([3, 1, 5, 12, 2, 11], 4), and why it won't create a new and empty heap and then add values to it, but keep the element from the previous call of the add function.

However, in this question Anther question, the max_sum will get reset each time.

Thanks for your help in advance.

question from:https://stackoverflow.com/questions/65940701/the-global-variable-declared-in-the-class-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...