defadd(self,item): temp = Node(item) temp.setNext(self.head) self.head = temp defsize(self): current = self.head count = 0 while current != None: count = count + 1 current = current.getNext()
return count
defsearch(self,item): current = self.head found = False while current != Noneandnot found: if current.getData() == item: found = True else: current = current.getNext()
return found
defremove(self,item): current = self.head previous = None found = False whilenot found: if current.getData() == item: found = True else: previous = current current = current.getNext()
if previous == None: self.head = current.getNext() else: previous.setNext(current.getNext())
defsearch(self,item): current = self.head found = False stop = False while current != Noneandnot found andnot stop: if current.getData() == item: found = True else: if current.getData() > item: stop = True else: current = current.getNext()
return found
defadd(self,item): current = self.head previous = None stop = False while current != Noneandnot stop: if current.getData() > item: stop = True else: previous = current current = current.getNext()
# q1 definfixToPostfix(infixexpr): """将表达式从中缀形式转化成后缀形式""" prec = {} prec["*"] = 3 prec["/"] = 3 prec["+"] = 2 prec["-"] = 2 prec["("] = 1 # 存储操作符的栈 opStack = Stack() postfixList = [] tokenList = infixexpr.split() # 栈中剩余的左括号的个数 left_p_remain = 0 for token in tokenList: if token in"ABCDEFGHIJKLMNOPQRSTUVWXYZ"or token in"0123456789": postfixList.append(token) elif token == '(': opStack.push(token) left_p_remain += 1 elif token == ')': left_p_remain -= 1 if left_p_remain < 0: raise Exception("parenthesis are not balance, please check!") 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) if left_p_remain != 0: raise Exception("parenthesis are not balance, please check!") whilenot opStack.isEmpty(): postfixList.append(opStack.pop())
return" ".join(postfixList)
print(infixToPostfix("A * B + C * D")) print(infixToPostfix("( A + B ) * C - ( D - E ) * ( F + G )")) print(infixToPostfix("( A + B ) * C - ( D - E ) ) * ( F + G)"))
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
A B * C D * + A B + C * D E - F G + * - --------------------------------------------------------------------------- Exception Traceback (most recent call last) <ipython-input-6-63343863e9e7> in <module>() 43 print(infixToPostfix("A * B + C * D")) 44 print(infixToPostfix("( A + B ) * C - ( D - E ) * ( F + G )")) ---> 45 print(infixToPostfix("( A + B ) * C - ( D - E ) ) * ( F + G)"))
<ipython-input-6-63343863e9e7> in infixToPostfix(infixexpr) 24 left_p_remain -= 1 25 if left_p_remain < 0: ---> 26 raise Exception("parenthesis are not balance, please check!") 27 topToken = opStack.pop() 28 while topToken != '(':
Exception: parenthesis are not balance, please check!
defqueue1_en_test(): q = Queue() for i inrange(1000): q.enqueue(1) defqueue2_en_test(): q = Queue2() for i inrange(1000): q.enqueue(1) defqueue1_en_de_test(): q = Queue() for i inrange(1000): q.enqueue(1) for i inrange(1000): q.dequeue() defqueue2_en_de_test(): q = Queue2() for i inrange(1000): q.enqueue(1) for i inrange(1000): q.dequeue()
# q7 classQueue3: """ Keep 2 stacks, let's call them inbox and outbox. Enqueue: Push the new element onto inbox Dequeue: If outbox is empty, refill it by popping each element from inbox and pushing it onto outbox Pop and return the top element from outbox """ def__init__(self): self.inbox = Stack() self.outbox = Stack()
An example[edit] Original, unsorted list: 170, 45, 75, 90, 802, 2, 24, 66 Sorting by least significant digit (1s place) gives: 170, 90, 802, 2, 24, 45, 75, 66 Notice that we keep 802 before 2, because 802 occurred before 2 in the original list, and similarly for pairs 170 & 90 and 45 & 75. Sorting by next digit (10s place) gives: 802, 2, 24, 45, 66, 170, 75, 90 Notice that 802 again comes before 2 as 802 comes before 2 in the previous list. Sorting by most significant digit (100s place) gives: 2, 24, 45, 66, 75, 90, 170, 802
# q10 defget_max_num_len(nums): """获取数组中位数最大的个数的位数""" max_len = 0 for num in nums: cur_len = 1 while num // 10 != 0: num = num // 10 cur_len += 1 if cur_len > max_len: max_len = cur_len return max_len
defget_num_by_order(num, order): """例如输入876和2,返回第二位的7;若输入4,则返回0""" left = num // (10**(order-1)) return left % 10
defradix_sorting_machine(nums): bins = [] for i inrange(10): bins.append(Queue()) for i inrange(get_max_num_len(nums)): for num in nums: bins[get_num_by_order(num, i+1)].enqueue(num) j = 0 for one_bin in bins: whilenot one_bin.isEmpty(): nums[j] = one_bin.dequeue() j += 1 return nums
def__init__(self): # 保存第一个结点 self.head = None self.length = 0 # 保存最后一个结点 self.rear = None # q16/q17 def__str__(self): datas = [] current = self.head while current: datas.append(current.getData()) current = current.getNext() datas = [str(data) for data in datas] return"[" + ",".join(datas) + "]" # q19 def__getitem__(self, key) : ifisinstance(key, slice) : #Get the start, stop, and step from the slice indices = list(range(self.size()))[key.start:key.stop:key.step] items = [] for ind in indices: items.append(self.__getitem__(ind)) return items elifisinstance(key, int) : if key < 0 : #Handle negative indices key += self.size() if key < 0or key >= self.size() : raise IndexError("The index (%d) is out of range."%key)
current = self.head cur_ind = 0 while cur_ind < key: current = current.getNext() cur_ind += 1 return current else: raise TypeError("Invalid argument type.") defisEmpty(self): returnself.head == None
defsearch(self,item): current = self.head found = False while current != Noneandnot found: if current.getData() == item: found = True else: current = current.getNext() return found
defremove(self,item): current = self.head previous = None found = False whilenot found and current: if current.getData() == item: found = True else: previous = current current = current.getNext() # q14 if found: if previous == None: self.head = current.getNext() else: previous.setNext(current.getNext()) # q13 self.length -= 1 else: print("item not found in the list!") # q18 defappend(self, item): """添加元素到尾部""" temp = Node(item) ifself.rear == None: self.rear = temp else: self.rear.setNext(temp) self.rear = temp ifself.head == None: self.head = temp self.length += 1 defindex(self, item): ind_list = [] current = self.head cur_ind = 0 while current: if current.getData() == item: ind_list.append(cur_ind) current = current.getNext() cur_ind += 1 return ind_list defpop(self, pos=0): if pos > self.size()-1: print("pos is bigger than list size!") return cur_ind = 1 pre = self.head current = pre.getNext() if pos == 0: self.head = current self.length -= 1 return pre.getData() while cur_ind < pos: pre = current current = pre.getNext() cur_ind += 1 # print(pre.getData()) pre.setNext(current.getNext()) self.length -= 1 return current.getData() definsert(self, pos, item): if pos > self.size(): print("pos is bigger than list size!") return if pos == 0: self.add(item) elif pos == self.size(): self.append(item) else: pre = self.head current = pre.getNext() cur_ind = 1 while cur_ind < pos: pre = current current = pre.getNext() cur_ind += 1 temp = Node(item) temp.setNext(current) pre.setNext(temp) self.length += 1
.input n
1 2 3 4 5
ul = UnorderedList() ul.add(1) ul.add(2) # q13 print(ul.size())
defsearch(self,item): current = self.head found = False stop = False while current != Noneandnot found andnot stop: if current.getData() == item: found = True else: if current.getData() > item: stop = True else: current = current.getNext()
return found
defadd(self,item): current = self.head previous = None stop = False while current != Noneandnot stop: if current.getData() > item: stop = True else: previous = current current = current.getNext()
defsize(self): current = self.head count = 0 while current != None: count = count + 1 current = current.getNext()
return count defremove(item): pre = self.head current = pre.getNext() if item == pre.getData(): self.head = current found = False stop = False while current andnot found andnot stop: if current.getData() == item: found = True else: if current.getData() > item: stop = True else: pre = current current = current.getNext() if found: pre.setNext(current.getNext()) defpop(self, pos=0): if pos > self.size()-1: print("pos is bigger than list size!") return cur_ind = 1 pre = self.head current = pre.getNext() if pos == 0: self.head = current return pre.getData() while cur_ind < pos: pre = current current = pre.getNext() cur_ind += 1 pre.setNext(current.getNext()) self.length -= 1 return current.getData() defindex(self, item): current = self.head cur_ind = 0 found = False stop = False while current != Noneandnot found andnot stop: if current.getData() == item: found = True else: if current.getData() > item: stop = True else: current = current.getNext() cur_ind += 1 if found: return cur_ind else: return -1
q21
考虑写一个Unordered list和 Ordered list 的父类,使得二者相同的操作可以在父类中实现。
deflist_test(): l = [] for i inrange(1000): l.append(i) for i inrange(1000): l.pop() defunorded_list_test(): ul = UnorderedList() for i inrange(1000): ul.add(i) for i inrange(1000): ul.pop()
defstack_1_test(): s = Stack() for i inrange(1000): s.push(i) for i inrange(1000): s.pop() defstack_2_test(): s = Stack2() for i inrange(1000): s.push(i) for i inrange(1000): s.pop() defqueue_1_test(): q = Queue() for i inrange(1000): q.enqueue(i) for i inrange(1000): q.dequeue() defqueue_2_test(): q = Queue2() for i inrange(1000): q.enqueue(i) for i inrange(1000): q.dequeue()