def createQVS(): """ This function creates stack1 to represent the front of the queue and stack2 which represents the back of the queue. finally the queue object is created and returned with all None and 0 values. :return: QueueViaStacks class object :rtype: queue """ stack1=myStack.Stack(None,0) stack2=myStack.Stack(None,0) return QueueViaStacks(stack1,stack2,0)
def run_game_sim(number_of_cards, number_of_rounds): """ this function controls gameplay. first, it initializes all the variables then, it iterates through each round. each round consists of resetting the round variables and shuffling the deck and deciding where the top card of the deck queue goes.that shuffling and deciding is a loop until the deck is exhausted, in which case the round statistics are completed finally, the game statistics are totaled and returned to the user. :param number_of_cards: the maximum number of cards for the deck :param type:int :param number_of_rounds: the maximum number of iterations to play :param type: int """ total_vp_size = 0 max_vp_size = 0 min_vp_size = 0 round_money_spent = 0 total_money_spent = 0 total_money_earned = 0 for round_count in range(1, (number_of_rounds + 1)): deck = get_deck(number_of_cards) discard1 = myStack.Stack(None, 0) discard2 = myStack.Stack(None, 0) vp = myStack.Stack(None, 0) while deck.size > 0: shuffle(deck) decide_card_destination(deck, discard1, discard2, vp) final_vp_check(number_of_cards, discard1, discard2, vp) round_money_spent += 5 total_money_earned += vp.size total_money_spent += round_money_spent total_vp_size += vp.size if vp.size > max_vp_size: max_vp_size = vp.size if vp.size < min_vp_size: min_vp_size = vp.size total_vp_size += vp.size print("Average victory pile size:", float(total_vp_size / number_of_rounds)) print("Max victory pile size:", max_vp_size) print("Min victory pile size:", min_vp_size) print("Total amount of money spent $", float(5 * number_of_rounds)) print("Total money won: $", float(total_money_earned)) print("Gross amount of money earned playing", number_of_rounds, "games $", float(total_money_earned - (5 * number_of_rounds)))
def test_isEmpty(self): try: s=myStack.Stack() #确保函数返回结果为True self.assertTrue(s.isEmpty()) self.fp.write('isEmpty passed\n') except Exception as e: self.fp.write('isEmpty failed\n')
def calculate(args): # make a Stack stackObject = myStack.Stack() # find operators for arg in args: # pop operands from stack when operator is found if arg in operators: # unary operators if arg == 'sqrt': # check underflow error, next in stack should be a number try: operand = stackObject.pop() answer = operators[arg](operand) # push the answer back onto the stack to keep evaluating # with this answer as the next possible operand stackObject.push(answer) except IndexError: print("Stack underflow error") return "DNE" # binary operators else: # check underflow error try: # second operand should be on top of stack secondOperand = stackObject.pop() firstOperand = stackObject.pop() # /0 error if arg == '/' and secondOperand == 0: print("Divide by zero error") return "DNE" else: # use operators to evaluate answer = operators[arg](firstOperand, secondOperand) # push answer back onto stack stackObject.push(answer) except IndexError: # if firstOperand not available print("Stack underflow error") return "DNE" # check for syntax error else: try: # push operands to stack # (if number then convert string to float and push) stackObject.push(float(arg)) except ValueError: # if not a number then it's a syntax error and doesn't push print("Syntax Error") return "DNE" # if no more operators found then pop final answer finalAnswer = stackObject.pop() # check if stack still contains more values for too many operands error if stackObject.size() > 0: print("Too many operands error") return "DNE" else: # and then return the popped final answer return finalAnswer
def test_isFull(self): try: s=myStack.Stack(3) s.push(1) s.push(2) s.push(3) self.assertTrue(s.isFull()) self.fp.write('isFull passed\n') except Exception as e: self.fp.write('isFull failed\n')
def test_empty(self): try: s=myStack.Stack(5) for i in ['a','b','c']: s.push(i) #测试清空栈操作是否工作正常1 s.empty() self.assertTrue(s.isEmpty()) self.fp.write('empty passed\n') except Exception as e: self.fp.write('empty failed\n')
def test_pushpop(self): try: s=myStack.Stack() s.push(3) #确保入栈后立刻出栈得到原来的元素 self.assertEqual(s.pop(),3) s.push('a') self.assertEqual(s.pop(),'a') self.fp.write('push and pop passed\n') except Exception as e: self.fp.write('push or pop failed\n')
def __init__(self, size=0): assert size >= 0, "Array size must be > 0" self.deleted = myStack.Stack( ) #initialise the stack for deleted indexes self._size = size #size of slots that are currently used self._rsize = size #size of slots that have been used before self._actualsize = size + 5 # Creates the array structure PyArrayType = ctypes.py_object * (size + 5) self._elements = PyArrayType() self.clear(None)
def decimal_to_byte(num): # 创建一个栈 stack = myStack.Stack() # 计算二进制 num = int(num) while num > 0: temp = num % 2 num = num / 2 stack.push(temp) # 将每一次%2的结果入栈 bytestr = "" while not stack.is_empty(): bytestr += str(stack.pop()) return bytestr
def divideBy2(num, base): digits = "0123456789ABCDEF" s = myStack.Stack() while num > 0: rem = num % base s.push(rem) num = num // base binaryStr = "" while not s.isEmpty(): binaryStr = binaryStr + digits[s.pop()] return binaryStr
def test_setSize(self): try: s=myStack.Stack(8) for i in range(8): s.push(i) self.assertTrue(s.isFull()) #测试扩大栈空间是否正常工作 s.setSize(9) s.push(8) self.assertTrue(s.isFull()) self.assertEqual(s.pop(),8) #测试缩小栈空间是否正常工作 s.setSize(4) self.assertTrue(s.isFull()) self.assertEqual(s.pop(),3) self.fp.write('setSize passed\n') except Exception as e: self.fp.write('setSize failed\n')
def checkParnthesis(sample): balanced = True index = 0 s = myStack.Stack() while index < len(sample) and balanced: symbol = sample[index] if symbol in "({[": s.push(symbol) else: if s.isEmpty(): balanced = False else: top = s.pop() if not matches(top, symbol): balanced = False index = index + 1 if balanced and s.isEmpty(): return balanced else: return False
import myStack as ms def parenCheck(pstring, ds): i = 0 while pstring[i] == '(': ds.push(pstring[i]) i += 1 while pstring[i] == ')': if ds.isEmpty(): return False else: ds.pop() i += 1 empty = (ds.isEmpty()) equaLen = (i == len(pstring)) if empty and equaLen: print("True") return True if not empty and equaLen: print("False") return False return parenCheck(pstring[i:], ds) ds = ms.Stack() parenCheck('((((()())))', ds)
class Stack: def __init__(self,size=10):#栈容量设定为10 self._content=[]#栈存储列表 self._size=size#栈容量 self._current=0#栈顶指针 def empty(self):#栈清空 self._content=[] self._current=0 def isEmpty(self):#判断栈是否为空 if not self._content: return True else: return False def setSize(self,size):#判断是否超出栈容量 if size<self._current: for i in range(size,self._current)[::-1]: del self._content[i]#超出则删除多余元素 self._current=size self._size=size def isFull(self):#判断栈是否为满 if self._current==self._size: return True else: return False def push(self,v):#压栈 if len(self._content)<self._size:#若栈未满 self._content.append(v)#压栈 self._current=self._current+1#栈指针后移 else: print('Stack Full! ')#否则输出栈已满 def pop(self):#弹出 if self._content:#若栈内存在元素 self._current=self._current-1#栈指针-1 return self._content.pop()#返回栈顶元素,即最后一位(此处与队列相反) else: print('Stack Empty! ')#否则输出栈为空 def show(self):#输出栈内所有元素值 print(self._content) def showRemainderSpace(self):#栈内剩余容量 print('Stack can still PUSH',self._size-self._current,'elements.') if __name__=='__main__': import myStack s=myStack.Stack() s.push(5) s.empty() print(s.pop(),'------') print(s.isEmpty()) print(s.isFull()) s.push(5) s.push(8) s.push('a') print(s.pop()) s.push('b') s.push('c') s.show() s.showRemainderSpace() s.setSize(3) print(s.isFull()) s.show() s.setSize(5) s.push('d') s.push('dddd') s.push(3) s.show() print('Please use me as a module.')
import myStack s = myStack.Stack() s.isEmpty() s.push(2) s.push(3) s.peek()
def initload(self,myfilename=""): # O n if myfilename == "": #no file name print("\nError: Please input the filename(where data will be retrived) within the parentheses of the load function\n") return False elif myfilename != "secretcode": #want to init from another file print("\nAre you sure?\nDoing this will override/erase all existing entries in this contactbook\n") if input("[Y/N] ") != "Y": print("Cancelled...") return False else: #use secretcode passphrase to prevent accidental init from database.nuode in event of myfilename is empty myfilename = "database.nuode" print("\nLoading data...") try: f = open(myfilename,"r") except: print("Uh-oh.. Looks like the file you requested for can't be found :((") return False contents = f.read() biglist = contents.split("\n") if len(biglist) == 0: print("Uh-oh.. Looks like the file you requested for is empty :((") return False #get my data self.mydata = self.listtoarray(ast.literal_eval(biglist[2])) #first get the python list back using ast then convert back into my own array data structure!! #get masterlist self.masterlist = self.listtoarray(ast.literal_eval(biglist[3])) #convert back to my own array data structure!! bigstack = myStack.Stack(biglist[4]) #reinitialise stack for deleted indexes for masterslist self.masterlist.deleted = bigstack treedict = ast.literal_eval(biglist[5]) #get treedict back for item in treedict: finaltree = self.rebuild(treedict[item]) #rebuild trees self.treedict[item] = finaltree date = int(biglist[1]) #get the date the contact book was last saved f.close() bdaynamelist = "" #live age updating if self.today != date: #if the contact book has a different date then need to update the ages print("Updating ages...") affectedlist = self.treedict["birthday[MMDD]"].getfromrange(int(str(date)[4:]),int(str(self.today)[4:])) #get the indexes in masterlist of affected users (whose birthday lie between when the contact book is last opened and today) if affectedlist != None: for num in affectedlist: loldata = self.masterlist[num] oldage = loldata[4] #find the old age loldata[4] = self.calcage(loldata[2]) # set it to the new age # do delete and insert operation for age tree for all the affected users self.treedict["age"].delete(oldage,num) #delete node with old age self.treedict["age"].insert(loldata[4],num) #add node with new age #birthday alert!! if loldata[5] == int(str(self.today)[4:]): #if the birthday of the user happens to be today, then append it to the birthday string congratsstring = "\t" + str(loldata[0]) + " " + str(loldata[1]) + " turns " + bcolors.OKGREEN + str(loldata[4]) + bcolors.ENDC + " today!" + "\n" bdaynamelist += congratsstring print("Done") print(bcolors.BOLD + "\nWelcome back,", self.mydata[0]," ٩(^ᴗ^)۶\n" + bcolors.ENDC) ##feature get today's birthday people and print birthday message if bdaynamelist != "": print("\nIt's the following people's birthday today 🎂🎂\nDon't forget to wish them a happy birthday!\n") print(bdaynamelist) self.autoload = True #set self.autoload to true return True
def clear(self, value): for i in range(self._rsize): self._elements[i] = value self.deleted = myStack.Stack()