第六章
本章详细叙述的栈和队列ADT模型,加强理解栈和队列与问题之间的转化。
但在6.30题还有疑问。
原著:
Alice has two queues, Q and R, which can store integers. Bob gives Alice
50 odd integers and 50 even integers and insists that she store all 100
integers in Q and R. They then play a game where Bob picks Q or R
at random and then applies the round-robin scheduler, described in the
chapter, to the chosen queue a random number of times. If the last number
to be processed at the end of this game was odd, Bob wins. Otherwise,
Alice wins. How can Alice allocate integers to queues to optimize her
chances of winning? What is her chance of winning?
汉译:
爱丽丝有两个用于存储整数的队列Q和R。鲍勃给了爱丽丝50个奇数和50个偶数,并坚持让他在队列Q和R存储所有100个整数。然后他们玩一个游戏,鲍勃从队列Q和R中随机选择元素(采用本章循环调度,对选择队列的次数是随机的)。如果游戏结束时被处理的最后一个数是奇数,则鲍勃胜。爱丽丝能如何分配整数到队列中来优化她获胜的机会?他获胜的机会是什么
我理解为先在R、Q中挑选一个队列,然后选择一个次数,在一个队列中循环执行入队出队的操作,直到最后一个数判断胜负。感觉这样的理解有些草率简单。如有更好的理解可以留言或者私信我。
代码中的Empty类需要自己手写,其它类引入源代码即可(我的资源中有发布的书籍源代码)
#6.1 会剩下一个5
#6.2 目前大小是18
#6.3
def transfer(S,T):
while len(S )!=1:
T.push(S.pop())
#6.4
def recursion(S):
if len(S)==0:
return
S.pop()
recursion(S)
#6.5
def reverse(lis):
from TheCode.ch06.array_stack import ArrayStack
S=ArrayStack()
for i in lis:
S.push(i)
for i in range(len(lis)):
lis[i]=S.pop()
#6.6
def text6(string,f=0,store=[]):
sign='({})'
if f==len(string):
if len(store)==0:
return True
else:
return False
if string[f] in sign[:len(sign)//2]:
store.append(string[f])
return text6(string,f+1,store)
elif string[f] in sign[len(sign)//2:]:
if string[f]==sign[len(sign)-sign.index(store.pop())-1]:
return text6(string,f+1,store)
else:
return False
else:
return text6(string,f+1,store)
#string='(123)'
#print(text6(string))
#6.7 会剩下4
#6.8 大小为27
#6.9 最终值为1~30,front在1~30中循环
#6.10 会使队列中元素混乱,因为它没用从逻辑上的第一个元素向新队列中添加
#6.11
class ADTqueue(object):
import collections
def __init__(self):
self._queue=collections.deque()
def __len__(self):
return len(self._queue)
def add(self,num):
self._queue.append(num)
def pop(self):
self._queue.popleft()
def first(self):
return self._queue[0]
#6.12 剩余 7 6 两个数,back()是什么函数
#6.13 使双端队列中第一个元素压入队列
def text13(D,Q):
while len(D)!=0:
Q.enqueue(D.delete_first())
#6.14 使双端队列中的第一个元素压入栈
def text14(D,S):
while len(D)!=0:
S.push(D.delete_first())
#6.15
#def text15(S):
# if S'last>S'top:
# x=S'last
# else:
# x=S'top
#全排列问题,设三个整数a>b>c,三个整数全排列总共有6种方式,这6种排序对应6种比较,有4种计较最大数参与比较
#这4种排序能得到最大值,其他的得不到最大值
#通过数学计算 , n个数只进行1次比较,得到最大数的概率为 2/n
#6.16
from TheCode.ch06.array_stack import ArrayStack
class ArrayStack1(ArrayStack):
def __init__(self,maxlen=None):
super().__init__()
self.maxlen=maxlen
#6.17
if maxlen!=None:
self._data=[None]*maxlen
def push(self,num):
if self.maxlen!=None and self.maxlen==len(self._data):
raise Exception('it is the fulled')
self._data.append(num)
self._size==1
#6.17 在ArrayStack1中更改了代码