这一讲主要介绍了两种数据结构:
-
stack 堆
设想放了一堆书,放的时候是从下往上放,拿的时候是从上往下拿,先拿最上面的,也就是最后放上的去的。所以是后进先出。
-
quene 队列
设想在排队,先到先得(First come, first served)。也就是说,先进来排队的人,先离开队伍。所以是先进先出。
这一周题目在此:题目
使用 python 来写数据结构的话非常方便。
第一个部分是写RandomizedQueue,它和 stack、quene类似,不同之处在于移除元素是随机的。代码如下:
import random
class RandomizedQueue:
#construct an empty randomized queue
Array = []
def __int__(self):
self.Array=[]
#return true if the queue is empty, false otherwise
def isEmpty(self):
return len(self.Array)==0
#insert the item into the queue
def add(self,item):
self.Array.append(item)
#delete and return an item from the queue, uniformly at random
def remove(self):
if self.isEmpty():
raise Exception('Empty!')
else:
remove_index = random.choice([i for i in range(len(self.Array))])
return self.Array.pop(remove_index)
测试结果 :
第二个部分是写Deque,它和 stack、quene类似,但是既可以在头部插入或者移除元素,也可以在尾部插入或者移除元素。代码如下:(为图方便,没有使用 Node添加 linked list)
class Deque:
#construct an empty deque
Array = []
def __init__(self):
self.Array=[]
#return true if the queue is empty, false otherwise
def isEmpty(self):
return len(self.Array)==0
#insert the item at the front of the queue
def addFirst(self,item):
self.Array.insert(0,item)
#insert the item at the end of the queue
def addLast(self, item):
self.Array.append(item)
#delete and return the first item in the queue
def removeFirst(self):
if self.isEmpty():
raise Exception('Empty!')
else:
return self.Array.pop(0)
#delete and return the last item in the queue
def removeLast(self):
if self.isEmpty():
raise Exception('Empty!')
else:
return self.Array.pop(-1)
测试结果:
第三个部分:
Given a command line parameter k k k, read in a sequence of strings from standard input, and print out a subset of exactly k k k of them, uniformly at random.
代码如下:
def Subset():
k = int(input('请输入要输出的个数 k: '))
RQ = RandomizedQueue()
while True:
strings = input('请输入一串字符,输入 # 结束:')
if strings!='#':
RQ.add(strings)
else:
break
print([RQ.remove() for i in range(k)])
运行结果如下:
第四个部分:
Read in a DNA sequence from standard input using StdIn.readChar. Determine whether the string represents a Watson-Crick complemented palindrome (the string equals its reverse when you replace each base with its complement: A-T, C-G). Palindromes in DNA have have many important biological roles. For example, tumor cells frequently amplify their genes by forming DNA palindromes.
代码如下:
def Palindrome():
string = input('输入一组DNA序列: ')
Dq1 = Deque()
Dq2 = Deque()
for i in string:
if i == 'A':
Dq1.addLast('A')
Dq2.addFirst('T')
elif i == 'T':
Dq1.addLast('T')
Dq2.addFirst('A')
elif i == 'G':
Dq1.addLast('G')
Dq2.addFirst('C')
elif i == 'C':
Dq1.addLast('C')
Dq2.addFirst('G')
if Dq1.Array==Dq2.Array:
print('Bingo!')
else:
print('Terrible!')
运行结果如下: