python优先队列,队列和栈

打印列表的疑问

class Node:
   def __str__(self):
      return "haha"

print([Node(),Node()])
print(Node())

输出为

[<__main__.Node object at 0x000000000311A208>, <__main__.Node object at 0x000000000311A358>]
haha

打印列表调用的不是每个元素str吗?看来不是,那调用的是什么.

一个简单的实例

在自定义结点的时候,需要实现__lt__()函数,这样优先队列才能够知道如何对结点进行排序.

import queue
import random

q = queue.PriorityQueue()


class Node:
   def __init__(self, x):
      self.x = x

   def __lt__(self, other):
      return other.x > self.x

   def __str__(self):
      return "{}".format(self.x)


a = [Node(int(random.uniform(0, 10))) for i in range(10)]
for i in a:
   print(i, end=' ')
   q.put(i)
print("=============")
while q.qsize():
   print(q.get(), end=' ')

队列的内部实现是二叉树形式的堆,它最大的缺点在于合并速度慢.然而实际应用中用到合并的场景并不多.如果非要使用可合并堆,可以用斐波那契堆或者二项堆或者左偏树等数据结构.

队列和栈

python列表十分强大,已经完全取代了栈和队列.只需要如下三个函数.

L.pop(index=len(L)-1) -> item -- remove and return item at index (default last).
Raises IndexError if list is empty or index is out of range.

L.insert(index, object) -- insert object before index

L.append(object) -> None -- append object to end

简单来说,就是4个操作:

入栈:stack.append(node)
弹栈:stack.pop()
入队:queue.append(node)
出队:queue.pop(0)

python中的mixin概念

mixin可以为类添加一种行为,它类似接口的概念,但是mixin允许实现许多函数.java现在也已经支持接口的默认函数了,这其实就相当于mixin.
它的实现方式是多继承.java中类的单继承叫"I am",接口的多继承叫"I can".

python的运算符重载

python2使用的只有一个返回int的cmp函数,python3换成了"富比较".只要实现了__lt__()函数就已经实现了__gt__,__le__等函数.但是没有实现eq函数,如下代码输出为False,因为没有实现eq函数.而大于号会调用小于号的实现.
要注意__lt__()函数返回的是bool值.

class Node:
   def __init__(self,x):
      self.x=x
   def __lt__(self, other):
      return self.x<other.x
print(Node(5)==Node(5)) 

可以定义一个Mixin

class ComparableMixin(object):

    def __eq__(self, other):
        if type(self) == type(None):
            if type(other) == type(None):
                return True
            else:
                return False
        elif type(other) == type(None):
            return False
        else:
            return not self<other and not other<self

    def __ne__(self, other):
        return not __eq__(self, other)

    def __gt__(self, other):
        return other<self

    def __ge__(self, other):
        return not self<other

    def __le__(self, other):
        return not other<self  

python中的排序

python2中的sort函数有cmp参数,python3中删掉了,于是只得通过key来指定比较的元素.排序也有两种方法,list.sort()或者是sorted()内置函数.

import random


def rand():
   return int(random.uniform(0, 10))


a = [(rand(), rand(), rand()) for i in range(10)]
print(a)
a.sort(key=lambda x: x[0] + x[1] + x[2])
print(a)
a = sorted(a, key=lambda x: (x[2], x[0], x[1]))
print(a)

转载于:https://www.cnblogs.com/weiyinfu/p/6144882.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值