Reputation: 355
Write a class and implement a list using embedded python list.
Input like : 4 9 3 5
Output should be like: 3 4 5 9
I use this code for taking the input values and split it to the list
s = input()
numbers = map(int, s.split())
How can i build up a class for this listPQ that takes the lists values and put, get and check if the list is empty?
To try if your queue works:
q = ListPQ()
q.put(3)
q.put(4)
x = q.get()
y = q.get()
print(x,y) #it should print 3 4
Upvotes: 1
Views: 260
Reputation: 6978
class ListPQ():
def __init__(self):
self.pq = []
def put(self, val):
# Write code to put the number and keep it in sorted way, however you decide to
# you can use self.pq to access the list and add stuff to it... this instance
# of the class will have it saved.
self.pq.append(val)
self.pq.sort() # This is just for brevity, you can use your own algo for this
def get(self):
# likewise, use the self.pq to pop it out like,
return self.pq.pop(-1)
def is_empty(self):
return len(self.pq) == 0
def __repr__(self):
return "<ListPQ: %r>" % self.pq
Now you can go ahead and use print(instance_of_listpq)
and this will print out the list as it's written in the __repr__
method.
Hope this helps now!
Upvotes: 1
Reputation: 3797
You could use the heapq module from the python standard library. Then it is even possible without a class.
Without class:
import heapq
h = []
heapq.heappush(h, 4)
heapq.heappush(h, 3)
heapq.heappush(h, 9)
heapq.heappush(h, 5)
print(heapq.heappop(h))
print(heapq.heappop(h))
print(heapq.heappop(h))
print(heapq.heappop(h))
the output would be (space instead of newline):
3 4 9 5
If you need a class you can do it as follows:
class ListPQ():
def __init__(self):
self.h = []
def put(self, item):
heapq.heappush(self.h, item)
def get(self):
return heapq.heappop(self.h)
Upvotes: 0