高级算法日记3:python数据结构之栈和队列

来源:互联网 发布:js contains方法 编辑:程序博客网 时间:2024/06/14 21:47

  • 废话
    • 1 list
    • 2 strings
    • 1 栈的数据结构
    • 2 栈的应用
      • 21括号顺序检测
      • 22 前中后缀表达式
    • 3 求解迷宫问题栈方法
  • 队列
    • 1 队列的数据结构

1.废话

在这一小节,我们用最快的速度,过一下python内置的一些比较重要的数据结构。

1.1 list

这里写图片描述

myList = [1024, 3, True, 6.5]myList.append(False)print(myList)myList.insert(2,4.5)print(myList)print(myList.pop())print(myList)print(myList.pop(1))print(myList)myList.pop(2)print(myList)myList.sort()print(myList)myList.reverse()print(myList)print(myList.count(6.5))print(myList.index(4.5))myList.remove(6.5)print(myList)del myList[0]print(myList)
[1024, 3, True, 6.5, False][1024, 3, 4.5, True, 6.5, False]False[1024, 3, 4.5, True, 6.5]3[1024, 4.5, True, 6.5][1024, 4.5, 6.5][4.5, 6.5, 1024][1024, 6.5, 4.5]12[1024, 4.5][4.5]

1.2 strings

更多关于字符串的操作,你可以参考《improve your python code(9)》

>>> myName'David'>>> myName.upper()'DAVID'>>> myName.center(10)'  David   '>>> myName.find('v')2>>> myName.split('v')['Da', 'id']

2. 栈

2.1 栈的数据结构

  1. Stack() creates a new stack that is empty. It needs no parameters and returns an empty stack.
  2. push(item) adds a new item to the top of the stack. It needs the item and returns nothing.
  3. pop() removes the top item from the stack. It needs no parameters and returns the item. The stack is modified.
  4. peek() returns the top item from the stack but does not remove it. It needs no parameters. The stack is not modified.
  5. isEmpty() tests to see whether the stack is empty. It needs no parameters and returns a boolean value.
  6. size() returns the number of items on the stack. It needs no parameters and returns an integer.
class Stack(object):    def __init__(self):        self.items = []    def isEmpty(self):        return self.items == []    def push(self,item):        self.items.append(item)    def pop(self):        return self.items.pop()    def peek(self):        return self.items[-1]    def size(self):        return len(self.items)

可以看到,在python中,栈这一数据结构完全可以用list实现和替代。

2.2 栈的应用

2.2.1.括号顺序检测

这里写图片描述

class Stack(object):    def __init__(self):        self.items = []    def isEmpty(self):        return self.items == []    def push(self,item):        self.items.append(item)    def pop(self):        return self.items.pop()    def peek(self):        return self.items[-1]    def size(self):        return len(self.items)def parChecker(inputstring):    s = Stack()    for letter in inputstring:        if letter == '(':            s.push(letter)        elif letter == ')':            if s.isEmpty():                return False            else:                s.pop()    return s.isEmpty()print(parChecker("((()))"))print(parChecker("(()"))print(parChecker("())"))
TrueFalseFalse

2.2.2 前/中/后缀表达式

什么是前/中/后缀表达式,这里不再赘述。
中缀表达式——>前缀表达式

def infixToPostfix(infixexpr):    prec = {}    prec["*"] = 3    prec["/"] = 3    prec["+"] = 2    prec["-"] = 2    prec["("] = 1    opStack = Stack()    postfixList = []    tokenList = infixexpr.split()    for token in tokenList:        if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789":            postfixList.append(token)        elif token == '(':            opStack.push(token)        elif token == ')':            topToken = opStack.pop()            while topToken != '(':                postfixList.append(topToken)                topToken = opStack.pop()        else:            while (not opStack.isEmpty()) and \               (prec[opStack.peek()] >= prec[token]):                  postfixList.append(opStack.pop())            opStack.push(token)    while not opStack.isEmpty():        postfixList.append(opStack.pop())    return " ".join(postfixList)print(infixToPostfix("A * B + C * D"))print(infixToPostfix("( A + B ) * C - ( D - E ) * ( F + G )"))

表达式——>后缀表达式

def postfixEval(postfixExpr):    operandStack = Stack()    tokenList = postfixExpr.split()    for token in tokenList:        if token in "0123456789":            operandStack.push(int(token))        else:            operand2 = operandStack.pop()            operand1 = operandStack.pop()            result = doMath(token,operand1,operand2)            operandStack.push(result)    return operandStack.pop()def doMath(op, op1, op2):    if op == "*":        return op1 * op2    elif op == "/":        return op1 / op2    elif op == "+":        return op1 + op2    else:        return op1 - op2print(postfixEval('7 8 + 3 2 + /'))

2.3 求解迷宫问题:栈方法

朕累了,先不写

3.队列

3.1 队列的数据结构

什么是队列?这就是队列:

这里写图片描述

本文的目标读者不是幼儿园小朋友。
队列的结构:
1. Queue() creates a new queue that is empty. It needs no parameters and returns an empty queue.
2. enqueue(item) adds a new item to the rear of the queue. It needs the item and returns nothing.
3. dequeue() removes the front item from the queue. It needs no parameters and returns the item. The queue is modified.
4. isEmpty() tests to see whether the queue is empty. It needs no parameters and returns a boolean value.
5. size() returns the number of items in the queue. It needs no parameters and returns an integer.

class Queue(object):    def __init__(self):        self.items = []    def isEmpty(self):        return self.items == []    def enqueue(self, item):        self.items.insert(0,item)    def dequeue(self):        return self.items.pop()    def size(self):        return len(self.items)

事实上,python3中,可以通过import queue导入第三方队列库。

原创粉丝点击