1

使用嵌入式 python 列表编写一个类并实现一个列表。

输入如:4 9 3 5

输出应该是:3 4 5 9

我使用此代码获取输入值并将其拆分到列表中

s = input()
numbers = map(int, s.split()) 

我如何为这个 listPQ 建立一个类,它接受列表值并放置、获取和检查列表是否为空?

要尝试您的队列是否有效:

   q = ListPQ()
   q.put(3)
   q.put(4)
   x = q.get()
   y = q.get()
   print(x,y)   #it should print 3 4
4

2 回答 2

1
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

现在您可以继续使用print(instance_of_listpq),这将打印出__repr__方法中写入的列表。

希望这对现在有帮助!

于 2013-09-16T11:55:18.900 回答
0

您可以使用 python 标准库中的heapq模块。然后甚至可以不用类。

无课:

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

输出将是(空格而不是换行符):

3 4 9 5

如果你需要一个类,你可以这样做:

class ListPQ():
    def __init__(self):
        self.h = []

    def put(self, item):
        heapq.heappush(self.h, item)

    def get(self):
        return heapq.heappop(self.h)
于 2013-09-16T12:04:25.890 回答