栈是一个特殊的有序列表,其插入和删除操作都在一端(栈顶)进行。
push():入栈, pop():出栈, isempty():判断是否是空栈, length():栈的长度, gettop():取栈顶元素
s = []
#入栈
s.append()
#出栈
s.pop()
#判断是否为空栈
not s
#栈的长度
len(s)
#取栈顶元素
s[-1]
1.括号匹配, 2.迷宫问题, 3.表达式求值, 4.背包问题
left = {'(', '[', '{'}
right = {')', ']', '}'}
s = []
def match(expr):
for c in expr:
if c in left:
s.append(c)
elif c in right:
if not s :
return False
if not 1 <= ord(c) - ord(s[-1]) <= 2 :
return False
s.pop()
return not s
import numpy as np
def initmaze():
maze = np.zeros((7,7))
walls = [
(1,3),
(2,1),(2,5),
(3,3),(3,4),
(4,2),
(5,4)
]
for i in range(7):
maze[i][0] = maze[i][-1] = 1
maze[0][i] = maze[-1][i] = 1
for i in walls:
maze[i[0]][i[1]] = 1
return maze
def path(maze, start ,end ):
i, j = start
ei, ej = end
s = [(i,j)]
maze[i][j] = 1
while s:
i, j = s[-1]
if (i,j) == (ei,ej):
break
for di, dj in [(0, -1), (0, 1), (-1, 0), (1, 0)]:
if maze[i + di][j + dj] == 0:
maze[i + di][j + dj] = 1
s.append((i + di, j + dj))
break
else:
s.pop()
return s
pn = initmaze()
print(pn)
print(path(pn,(1,1),(5,5)))
operators = {
'+' : lambda op1, op2: op1 + op2,
'-' : lambda op1, op2: op1 - op2,
'*' : lambda op1, op2: op1 * op2,
'/' : lambda op1, op2: op1 / op2,
}
def postfix(e):
tokens = e.split()
s = []
for token in tokens:
if token.isdigit():
s.append(int(token))
elif token in operators:
f = operators[token] # 此处必须用中括号
op2 = s.pop()
op1 = s.pop()
s.append(f(op1,op2))
return s.pop()
print(postfix('2 3 4 * +'))
# 背包问题
def knapsack(t, w):
n = len(w)
s = []
k = 0
while s or k < n:
while t > 0 and k < n:
if t >= w[k]:
s.append(k)
t -= w[k]
k += 1
if t == 0:
print(s)
k = s.pop()
t += w[k]
k += 1
knapsack(10,[1,8,4,3,5,2])