数据结构与算法python语言实现-第六章答案
6.2
15-18
6.3
def transfer(S,T):
while S:
T.append(S.pop())
a=[1,2,3,4]
b=[]
transfer(a,b)
print(a,b)
6.5
def reverse(S):
A = []
while S:
A.append(S.pop())
while A:
S.append(A.pop(0))
return S
#列表传入函数,可变数据类型,可变对象
#直接改变引用不能改变变量在外部的情况,对列表变量内部操作才能将变化保留至外部
#指操作S=copy.deepcopy(A)
if __name__ == '__main__':
S = [0, 1, 2, 3, 5]
print(reverse(S), S)
print(S)
6.6
def match(s,tag=[],n=0):
lefty='{[('
righty='}])'
if s[n] in lefty:
tag.append(s[n])
elif s[n] in righty:
if len(tag)==0:
return False
if lefty.index(tag.pop())!=righty.index(s[n]):
return False
if n == len(s) - 1:
return not bool(len(tag))
return match(s, tag, n + 1)
s='(3+5)/3+{}[=()]'
print(match(s))
s='((3+5)/3+{}[=()]'
print(match(s))
6.10
class Empty(Exception):
pass
class ArrayQueue:
"""FIFO queue implementation using a Python list as underlying storage."""
DEFAULT_CAPACITY = 10 # moderate capacity for all new queues
def __init__(self):
"""Create an empty queue."""
self._data = [None] * ArrayQueue.DEFAULT_CAPACITY
self._size = 0
self._front = 0
def __len__(self):
"""Return the number of elements in the queue."""
return self._size
def is_empty(self):
"""Return True if the queue is empty."""
return self._size == 0
def first(self):
"""Return (but do not remove) the element at the front of the queue.
Raise Empty exception if the queue is empty.
"""
if self.is_empty():
raise Empty('Queue is empty')
return self._data[self._front]
def dequeue(self):
"""Remove and return the first element of the queue (i.e., FIFO).
Raise Empty exception if the queue is empty.
"""
if self.is_empty():
raise Empty('Queue is empty')
answer = self._data[self._front]
self._data[self._front] = None # help garbage collection
self._front = (self._front + 1) % len(self._data)
self._size -= 1
return answer
def enqueue(self, e):
"""Add an element to the back of queue."""
if self._size == len(self._data):
self._resize(2 * len(self.data)) # double the array size
avail = (self._front + self._size) % len(self._data)
self._data[avail] = e
self._size += 1
def _resize(self, cap): # we assume cap >= len(self)
"""Resize to a new list of capacity >= len(self)."""
old = self._data # keep track of existing list
self._data = [None] * cap # allocate list with new capacity
walk = self._front
for k in range(self._size): # only consider existing elements
self._data[k] = old[walk] # intentionally shift indices
walk = (1 + walk) % len(old) # use old size as modulus
self._front = 0 # front has been realigned
# 队列整体没有变化,依然填充了之前的数组空间,无法跟进添加元素,增加队列。
6.13
from collections import deque
from queue import Queue
D=deque()
D.extend(i for i in range(1,9))
Q=Queue()
Q.put(D.pop())#8
Q.put(D.pop())#7
Q.put(D.pop())#6
D.appendleft(D.pop())#5放在左边 D为51234
Q.put(D.pop())#D 5123
Q.put(D.popleft())#D 123 Q 87645
Q.put(D.pop())#3
Q.put(D.pop())#2
Q.put(D.pop())#1
D.appendleft(Q.get())
D.appendleft(Q.get())
D.appendleft(Q.get())
D.appendleft(Q.get())
D.appendleft(Q.get())
D.appendleft(Q.get())
D.appendleft(Q.get())
D.appendleft(Q.get())
print(D)
6.14
from collections import deque
D=deque()
D.extend(i for i in range(1,9))
Q=[]
Q.append(D.pop())#8
Q.append(D.pop())#7
Q.append(D.pop())#6
Q.append(D.popleft())#1
Q.append(D.popleft())#2
Q.append(D.popleft())#3
Q.append(D.popleft())#4
D.append(Q.pop())#4
D.appendleft(Q.pop())#3
D.appendleft(Q.pop())#2
D.appendleft(Q.pop())#1
D.append(Q.pop())#6
D.append(Q.pop())#7
D.append(Q.pop())#8
print(D)
6.20
def permutationN(n):
a = [None] * n
for i in range(n):
a[i] = i + 1
sum = 1
for j in range(n):
sum *= (j + 1)
i = 0
for k in range(sum):
# If you want to use stack
# a[i:i+2]=swapStack(a[i],a[i+1])
a[i:i + 2] = [a[i + 1], a[i]]
print(a)
i += 1
if i == (n - 1):
i = 0
permutationN(3)
6.21
def enumerate(n):
s=[]
t=[i for i in range(1,n+1)]
while t:
s.append(t)
print(s)
t.pop()
return s
#append传递的也是引用
print(enumerate(4))