Home > other >  Why do I get TypeError, when trying to find the max element of a heap with function 'nlargest&#
Why do I get TypeError, when trying to find the max element of a heap with function 'nlargest&#

Time:05-22

I was trying to find the maximum element of a heap and found a function heapq.nlargest to use.

Then got this error at the line commented below:

TypeError at line 10: 'NoneType' object is not iterable.

So here is the code:

from heapq import *
from math import ceil

number_of_elements, size_of_window = 10, 10
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
first_window = sorted(array[:size_of_window])
lower_set = first_window[:ceil(size_of_window / 2)]
lower_set_heap = heapify(lower_set)
print(nlargest(1,lower_set_heap))  # got TypeError here

CodePudding user response:

heapify modifies the argument in-place:

heapq.heapify(x)

Transform list x into a heap, in-place, in linear time.

Thus, in lower_set_heap = heapify(lower_set), lower_set_heap will be None:

>>> lower_set_heap = heapify(lower_set)
>>> lower_set_heap is None
True

You should just write heapify(lower_set) and then lower_set is your heap:

>>> heapify(lower_set) # modifies `lower_set`
>>> print(nlargest(1,lower_set))
[5]

CodePudding user response:

Why do we need to heapify fist? Instead we could just call nlargest directly?

from heapq
from math import ceil

number_of_elements, size_of_window = 10, 10
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

first_window = sorted(array[:size_of_window])
lower_set = first_window[:ceil(size_of_window / 2)]

# (1) just return the largest
print(heapq.nlargest(1, lower_set))

# (2) fixed solution: why heapify first?
heapq.heapify(lower_set)  # Attention: modifies list in_place
print(heapq.nlargest(1,lower_set))

Both print the same:

[5]
[5]

See also

  • Related