0

I need to create and use n heaps, I am trying to use heapq and is trying to push elements into a list of lists, where each element is to be considered a seperate heap. But its behaving weirdly. I just wanna push the elements 6 and 7 into my 3rd heap. but its getting pushed into all my heaps. any way out of this??

>>> test
[[], [], [], []]
>>> 
>>> heappush(test[2],6)
>>> heappush(test[2],7)
>>> test
[[6, 7], [6, 7], [6, 7], [6, 7]]
JATMON
  • 1,000
  • 1
  • 8
  • 14

2 Answers2

3

You seem to have created test something like this:

>>> from heapq import heappush
>>> test = [[]] * 4
>>>
>>> heappush(test[2],6)
>>> heappush(test[2],7)
>>> test
[[6, 7], [6, 7], [6, 7], [6, 7]]

This creates four references to the same list object. Use a list comprehension to make four distinct lists:

>>> test = [[] for _ in range(4)]
>>> heappush(test[2],6)
>>> heappush(test[2],7)
>>> test
[[], [], [6, 7], []]
Blender
  • 289,723
  • 53
  • 439
  • 496
2

You are using the same heap instance for all the heaps. Are you perhaps doing something like this?

test = [ [] * 4]

You need to create four distinct heaps instead. Exactly how depends on what you are doing now.

Lennart Regebro
  • 167,292
  • 41
  • 224
  • 251