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

本文快速介绍了Python中的几种基本数据结构,包括列表(list)的操作方法、字符串(string)的基本使用,详细讲解了栈(stack)的数据结构及应用,如括号匹配检测和表达式转换,并简要介绍了队列(queue)的数据结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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]
1
2
[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("())"))
True
False
False

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

print(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导入第三方队列库。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值