How Do References In Functions Work?
First I wrote the first sample of code and it didn't work correctly. I prefer the first sample, but only the second one works correctly. I don't know why the first sample doesn't c
Solution 1:
You could also use [:]
, that will change the original object passed in:
def heap_sort(tab):
heap = []
for i in tab:
heapq.heappush(heap, i)
tab[:] = [heapq.heappop(heap) for _ in xrange(len(heap))]
So instead of reassigning the name tab
to a new object you are actually updating the original tab
object.
You could also use a generator expression instead of building the whole list:
tab[:] = (heapq.heappop(heap) for _ in xrange(len(heap)))
Solution 2:
Because you're just reassigning a new name called tab
inside the function, it doesn't affect the global name tab
you've defined.
So, change your function to actually return the value, will work:
import heapq
defheap_sort(tab):
heap = []
for i in tab:
heapq.heappush(heap, i)
# return the supposed tab valuereturn [heapq.heappop(heap) for _ in xrange(len(heap))]
tab = [4, 3, 5, 1]
# assign the tab to the returned value
tab = heap_sort(tab)
print tab
[1, 3, 4, 5]
For your reference, read How do I pass a variable by reference? will help you understand how the referencing works in Python.
Solution 3:
Try this:
>>>defheap_sort(tab):
heap=[]
for i in tab:
heapq.heappush(heap,i)
heapq.heapify(heap)
return heap
>>>t=heap_sort(t)>>>print(t)
[1, 3, 5, 4]
Post a Comment for "How Do References In Functions Work?"