def divideBy2(num): remstack = Stack() while num > 0: rem = num % 2 remstack.push(rem) num = num // 2
class DirectedCycle: def __init__(self,digraph): self.marked = [False] * (digraph.v + 1) self.edgeTo = [None] * (digraph.v +1) self.cycle = None self.onStack = [False] * (digraph.v +1) for v in range(digraph.v +1): if self.marked[v] is False: self._dfs(digraph,v) def _dfs(self,dg,v): self.onStack[v] = True self.marked[v] = True for w in dg.adj(v): if (self.hasCycle()): return elif (self.marked[w] is False): self.edgeTo[w] = v self._dfs(dg,w) elif(self.onStack[w]): self.cycle = Stack() x = self.edgeTo[v] while(x != w): self.cycle.push(x) self.cycle.push(w) self.cycle.push(v) self.onStack[v] = False def hasCycle(self): return self.cycle is not None
def TestInput(inputStr): s = Stack(); for i in inputStr: if i == '(' or i == '[' or i == '{': s.push(i) elif i == ')' or i == ']' or i == '}': temp = s.pop() if temp == '(': if i == ']' or i == '}': return False elif temp == '[': if i == '(' or i == '}': return False if temp == '{': if i == ']' or i == ')': return False return True
class DepthFirstOrder: def __init__(self,digraph): self._pre = Queue() self._post = Queue() self._reversePost = Stack() self._marked = [False] * (digraph.v +1) for v in range(digraph.v +1): if self._marked[v] is False: self._dfs(digraph,v) def _dfs(self,dg,v): self._pre.enqueue(v) self._marked[v] = True for w in dg.adj(v): if self._marked[w] is False: self._dfs(dg,w) self._post.enqueue(v) self._reversePost.push(v) def pre(self): return self._pre def post(self): return self._post def reversePost(self): return self._reversePost
class Queue(object): def __init__(self): self.newStack = Stack() self.oldStack = Stack() def add(self, item): self.newStack.push(item) def remove(self): if self.oldStack.isEmpty(): self.transferStacks() return self.oldStack.pop() def peek(self): if self.oldStack.isEmpty(): self.transferStacks() return self.oldStack.pop() def transferStacks(self): while not self.newStack.isEmpty(): popped = self.newStack.pop() self.oldStack.push(popped)
def genrate_actualtour(self, StartCity): """ This method generates the graph of the bestTour. It calls the move_branch method with a given StartCity. From the bestTour stack it filters out only the interestCities by leaving out all the intersection points. It then creates an instance of graph class in the same order as in bestTour. """ tour = Stack() # create a new stack self.currentTour.push(StartCity) # push the startCity in currentTour stack self.mark_visit(StartCity) # mark it visited self.move_branch(StartCity) # call move_branch recursive function, with the given city # The following block of code removes vertices from bestTour and filters out # only the interest points and adds it to tour Stack while self.bestTour.size() != 0: city = self.bestTour.pop() if city in self.interestCities: tour.push(city) # The following block of code generates a Graph object from the tour Stack newGraph = Graph(tour.items) # adds only the vertices in the graph for i in range(len(tour.items)-1): newEdge = Edge(tour.items[i], tour.items[i+1]) # create an edge within two consecutive vertices newGraph.add_edge(newEdge) # add the edge to the graph return newGraph
def rev_str(str): s = Stack() for i in str: s.push(i) rev = "" while not s.is_empty(): rev += s.pop() return rev
def reverse(a): stack = Stack() for x in a: stack.push(x) answer = "" while not stack.isEmpty(): answer = answer + stack.pop() return answer
def __init__(self, diskNumber = 4): assert(diskNumber > 0) self.diskNumber = diskNumber self.towerA = Stack() self.towerB = Stack() self.towerC = Stack() for i in xrange(diskNumber): diskIndex = diskNumber - i self.towerA.push(diskIndex)
def reverseString(stringToReverse): stackList = Stack() for char in stringToReverse: stackList.push(char) newString = "" while not stackList.isEmpty(): newString += stackList.pop() return newString
def decToBin(dec): remStack = Stack() bin = '' while dec > 0: remStack.push(dec % 2) dec //= 2 while not remStack.isEmpty(): bin += str(remStack.pop()) return bin
def sortStack(stacks): buffer = Stack() while(stacks.size !=0): temp = stacks.pop() while(buffer.size !=0 and temp < buffer.peek()): stacks.push(buffer.pop()) buffer.push(temp) return buffer
def test_len(self): ''' Test Len :return: ''' s = Stack() s.push("One") self.assertEquals(1,len(s))
def __init__(self, cities=[]): self.currentTour = Stack() self.bestTour = Stack() self.currentCost = 0 self.bestCost = 10000000000000000000000000000000 self.interestCities = [Vertex(city) for city in cities] self._map = Graph() self._visitedPoints = [] self._visitedCities = []
def tenToTwo(toConvert): stack = Stack() while toConvert > 0: stack.push(toConvert % 2) toConvert = toConvert // 2 # integer division answer = "" while not stack.isEmpty(): answer = answer + str(stack.pop()) return answer
def sortStack(s): stackA = s stackB = Stack() while not stackA.isEmpty(): maxm = popA(stackA) pushB(stackA, stackB, maxm) while not stackB.isEmpty(): stackA.push(stackB.pop())
def testLen(self): #initialize the stack s = Stack() #push three itmes into the stack for i in range(3): s.push(i) #Check the length self.assertEqual(len(s),3)
def revstring(mystr): myStack = Stack() for ch in mystr: myStack.push(ch) revstr='' while not myStack.isEmpty(): revstr = revstr + myStack.pop() return revstr
def printContents(self): s = Stack() print("Contents of Stack " + str(self.index)) while not self.stack.empty(): disk = self.stack.pop() print(disk) s.push(disk) while not s.empty(): self.stack.push(s.pop())
def buildParseTree(fpexp): fplist = fpexp.split() pStack = Stack() eTree = BinaryTree('') pStack.push(eTree) currentTree = eTree for i in fplist: if i == '(': currentTree.insertLeft('') pStack.push(currentTree) currentTree = currentTree.getLeftChild() elif i not in ['+', '-', '*', '/', ')']: currentTree.setRootVal(int(i)) parent = pStack.pop() currentTree = parent elif i in ['+', '-', '*', '/']: currentTree.setRootVal(i) currentTree.insertRight('') pStack.push(currentTree) currentTree = currentTree.getRightChild() elif i == ')': currentTree = pStack.pop() else: raise ValueError return eTree
class StackWithMin(Stack): def __init__(self, *args, **kwargs): super(StackWithMin, self).__init__(*args, **kwargs) self.min_stack = Stack() def push(self, data): new_node = Node(data) new_node.set_next(self.head) self.head = new_node try: min = self.min_stack.peek() if data <= min: self.min_stack.push(data) except Stack.Empty: self.min_stack.push(data) def pop(self): value = super(StackWithMin, self).pop() if value == self.min_stack.peek(): self.min_stack.pop() return value def min(self): return self.min_stack.peek()
def TopologicalSort(self): s = Stack(len(self.V) + 1) S = [] for v in self.V: v.parent = None v.colour = white v.d = v.f = inf time = 0 s.push(self.V[0]) while not s.isEmpty(): v = s.top() if v.colour == white: v.colour = grey v.d = time = time + 1 for u in v.adjacent: if u.colour == white: u.parent = v s.push(u) break if u.colour != white: v.f = time = time + 1 v.colour = black S.insert(0, v) s.pop() return S
def __init__(self): """Initializes all of the instance variables""" self.myCurrent = None # my currently displayed card self.otherCurrent = None # other currently displayed card self.currentState = 0 # keeps track of the state of play self.dealingPile = Stack() # stack self.myPlayingPile = Stack() # stack self.myStoragePile = Queue()# queue self.otherPlayingPile = Stack()# stack self.otherStoragePile = Queue()# queue self.lootPile = Queue() # queue
def devBy2(Number): storageStack = Stack() binaryData = "" while Number > 0: storageStack.push(Number%2) Number = Number // 2 while not storageStack.isEmpty(): binaryData = binaryData + str(storageStack.pop()) return binaryData
def binaryConverter(decimal_number): # defined for whole numbers ( n > 0) s = Stack() while decimal_number > 0: s.push( decimal_number % 2 ) decimal_number = decimal_number // 2 binary_string = '' while not s.is_empty(): binary_string += str( s.pop() ) return binary_string
def save_poles(poles): # duplicating poles a, b, c = Stack(), Stack(), Stack() a.copyFrom(poles[0]) b.copyFrom(poles[1]) c.copyFrom(poles[2]) saved = [a, b, c] return saved
def testpopEmpty_empty(self): # First of a series of tests to check proper exception being thrown by a # violation of precondition. In this case, the pop() from an empty stack. s = Stack() #first Test Case try: val = s.pop() self.assertTrue(False, "No exception / or not right type of excpetion rasied for pop of empty stack") except IndexError: self.assertTrue(True)
def revStr(strToRev): s = Stack() for x in strToRev: s.push(x) a = '' while not s.isEmpty(): a = a + s.pop() return a
def devByX(Number, base): digits="0123456789ABCDEF" storageStack = Stack() binaryData = "" while Number > 0: storageStack.push(Number%base) Number = Number // base while not storageStack.isEmpty(): binaryData = binaryData + digits[storageStack.pop()] return binaryData
def reverseString(st): s = Stack() stLen = len(st) for i in range(stLen): s.push(st[i]) outStr = [] for i in range(stLen): outStr.append(s.pop()) rev = ''.join(outStr) return rev
def __init__(self): self.stack1 = Stack() self.stack2 = Stack()
from Stack import Stack arrayStack = Stack() arrayStack.push(5) # contents: [5] arrayStack.push(3) # contents: [5, 3] print(arrayStack.size()) # contents: [5, 3]; outputs 2 print(arrayStack.pop()) # contents: [5]; outputs 3 print(arrayStack.isEmpty()) # contents: [5]; outputs False print(arrayStack.pop()) # contents: [ ]; outputs 5 print(arrayStack.isEmpty()) # contents: [ ]; outputs True arrayStack.push(7) # contents: [7] arrayStack.push(9) # contents: [7, 9] print(arrayStack.top()) # contents: [7, 9]; outputs 9 arrayStack.push(4) # contents: [7, 9, 4] print(arrayStack.size()) # contents: [7, 9, 4]; outputs 3 print(arrayStack.pop()) # contents: [7, 9]; outputs 4 arrayStack.push(6) # contents: [7, 9, 6]
def push(self, item): if self.list[-1].size() == self.stackSize: self.list.append(Stack()) self.list[-1].push(item)
def __init__(self, stackSize=5): self.list = [] self.list.append(Stack()) self.stackSize = stackSize
class LaberintoADT: ''' 0 pasillo, 1 pared, S salida y E entrada pasillo es una tupla ((2, 1), (2, 2), (2, 3 ), (2, 4), (3, 2), (4, 2)) entrada en una tupla (5, 1) salida (2, 5) ''' def __init__(self, rens, cols, pasillos, entrada, salida): self.__laberinto = Array2D(rens, cols, '1') for pasillo in pasillos: self.__laberinto.set_item(pasillo[0], pasillo[1], '0') self.set_entrada(entrada[0], entrada[1]) self.set_salida(salida[0], salida[1]) self.__camino = Stack() self.__previa = None #Guardará la posición previa def to_string(self): #Muestra el laberinto self.__laberinto.to_string() #Establece la entrada 'E' en la matriz, verificar límites. def set_entrada(self, ren, col): # Terminar la validación de las coordenadas self.__laberinto.set_item(ren, col, 'E') #Establece la salida 'S' en la matriz, verificar límites periféricos def set_salida(self, ren, col): #Terminar las validaciiones self.__laberinto.set_item(ren, col, 'S') def es_salida(self, ren, col): return self.__laberinto.get_item(ren, col) == 'S' def buscar_entrada(self): #Busca la posición de la entrada y la mete a la pila encontrado = False for renglon in range(self.__laberinto.get_num_rows()): for columna in range(self.__laberinto.get_num_cols()): tope = self.__camino.peek() #Tupla if self.__laberinto.get_item(tope[0, tope[1]]) == 'E': self.__camino.push((renglon, columna)) encontrado = True return encontrado def set_previa(self, pos_previa): self.__previa = pos_previa def get_previa(self): return self.__previa def imprimir_camino(self): self.__camino.to_string() def get_pos_actual(self): return self.__camino.peek() def resolver_laberinto(self): #Aplicar reglas actual = self.__camino.peek() #(5, 2) #Buscar izquierda if actual[1]-1 != -1 \ and self.__laberinto.get_item(actual[0], actual[1]-1) == '0' \ and self.get_previa() != (actualactual[0], actual[1]-1) \ and self.__laberinto.get_item(actual[0], actual[1]-1) != 'X': self.set_previa(actual) self.__camino.push((actual[0], actual[1]-1)) #Buscar arriba elif actual[1]-1 != -1 \ and self.__laberinto.get_item(actual[0]-1, actual[1]) == '0' \ and self.get_previa() != (actualactual[0]-1, actual[1]) \ and self.__laberinto.get_item(actual[0]-1, actual[1]-1) != 'X': self.set_previa(actual) self.__camino.push((actual[0]-1, actual[1])) #Buscar derecha elif 1==0: pass #Buscar abajo elif 1==0: pass else: self.__laberinto.set_item(actual[0] actual[1], 'X') self.__previa = actual self.__camino.pop()
from Stack import Stack def sort_stack(stack): if stack.isEmpty(): return stack out = Stack() while not stack.isEmpty(): temp = stack.pop() while not out.isEmpty() and out.peek() > temp: stack.push(out.pop()) out.push(temp) return out arr = [1, 4, 10, 5, 6] stack = Stack() for n in arr: stack.push(n) sorted_stack = sort_stack(stack) out = [] while not sorted_stack.isEmpty(): x = sorted_stack.pop() out.append(x) print(out)
from Stack import Stack s = Stack() print(s.isEmpty()) s.push(10) s.push(20) s.push(30) print(s.pop()) print(s.peek()) print(s.size())
from Stack import Stack stack = Stack() stack.push(5) stack.push(6) print stack.pop() stack.push(7) print stack.pop() print stack.pop() print stack.pop()
from Stack import Stack stack = Stack() assert stack.is_empty() is True stack.push(1) assert stack.is_empty() is False stack.push(2) assert stack.size() == 2 assert stack.peek() == 2 assert stack.size() == 2 assert stack.pop() == 2 assert stack.size() == 1 assert stack.peek() == 1 assert stack.size() == 1 assert stack.pop() == 1 assert stack.size() == 0 assert stack.is_empty() is True
def p_match(expression): # if type(expression) is not '<class \'str\'>': # raise Exception("Passed object is not String, its",type(expression)) brackets = ["(", "[", "{", ")", "]", "}"] right_bracket = brackets[3:] left_bracket = brackets[:2] eqn_str = expression # eqn_str = "[(){()[]}]" eqn_stack = Stack() for x in eqn_str: if x in brackets: eqn_stack.push(x) s = Stack() i = eqn_stack.get_top() while i: i -= 1 # print("\nTop:", eqn_stack.get_top()) if eqn_stack.get_data() in right_bracket: # print("Right Bracket") s.push(eqn_stack.pop()) # print("s top:", s.get_top()) else: # print("Left Bracket") # print("s top:", s.get_top()) if eqn_stack.get_data() == '[': if s.get_data() == ']': # print("Match") eqn_stack.pop() s.pop() elif eqn_stack.get_data() == '(': if s.get_data() == ')': # print("Match") eqn_stack.pop() s.pop() elif eqn_stack.get_data() == '{': if s.get_data() == '}': # print("Match") eqn_stack.pop() s.pop() if s.get_top() == eqn_stack.get_top(): return 1 else: return 0
class UI: LOAD_TAB = 0 ALIGN_TAB = 1 STACK_TAB = 2 SHARPEN_TAB = 3 TITLE = "AstraStack" VERSION = "2.0.0" def __init__(self): self.parentConn, self.childConn = Pipe(duplex=True) self.pids = [] self.newVersionUrl = "" self.video = None self.align = None self.stack = None self.sharpen = None self.mousePosition = None self.clickedDriftP1 = False self.clickedDriftP2 = False self.clickedAreaOfInterest = False self.builder = Gtk.Builder() self.builder.add_from_file("ui/ui.glade") self.window = self.builder.get_object("mainWindow") self.saveDialog = self.builder.get_object("saveDialog") self.openDialog = self.builder.get_object("openDialog") self.tabs = self.builder.get_object("tabs") self.cpus = self.builder.get_object("cpus") self.progressBox = self.builder.get_object("progressBox") self.progress = self.builder.get_object("progress") self.frame = self.builder.get_object("frame") self.overlay = self.builder.get_object("overlay") self.frameSlider = self.builder.get_object("frameSlider") self.frameScale = self.builder.get_object("frameScale") self.startFrame = self.builder.get_object("startFrame") self.endFrame = self.builder.get_object("endFrame") self.normalize = self.builder.get_object("normalize") self.alignChannels = self.builder.get_object("alignChannels") self.autoCrop = self.builder.get_object("autoCrop") self.transformation = self.builder.get_object("transformation") self.drizzleFactor = self.builder.get_object("drizzleFactor") self.drizzleInterpolation = self.builder.get_object( "drizzleInterpolation") self.limit = self.builder.get_object("limit") self.limitPercent = self.builder.get_object("limitPercent") self.averageRadio = self.builder.get_object("averageRadio") self.medianRadio = self.builder.get_object("medianRadio") self.openDialog.set_preview_widget(Gtk.Image()) self.saveDialog.set_preview_widget(Gtk.Image()) self.builder.get_object("alignTab").set_sensitive(False) self.builder.get_object("stackTab").set_sensitive(False) self.builder.get_object("processTab").set_sensitive(False) self.builder.get_object("blackLevel").add_mark(0, Gtk.PositionType.TOP, None) self.builder.get_object("gamma").add_mark(100, Gtk.PositionType.TOP, None) self.builder.get_object("value").add_mark(100, Gtk.PositionType.TOP, None) self.builder.get_object("red").add_mark(100, Gtk.PositionType.TOP, None) self.builder.get_object("green").add_mark(100, Gtk.PositionType.TOP, None) self.builder.get_object("blue").add_mark(100, Gtk.PositionType.TOP, None) self.builder.get_object("saturation").add_mark(100, Gtk.PositionType.TOP, None) self.disableScroll() self.cpus.set_upper(min( 61, cpu_count())) # 61 is the maximum that Windows allows self.cpus.set_value(min(61, math.ceil(cpu_count() / 2))) g.pool = None self.processThread = None self.builder.connect_signals(self) # Needed so it can be temporarily removed self.limitPercentSignal = self.limitPercent.connect( "value-changed", self.setLimitPercent) g.driftP1 = (0, 0) g.driftP2 = (0, 0) g.areaOfInterestP1 = (0, 0) g.areaOfInterestP2 = (0, 0) self.window.show_all() self.checkNewVersion() self.setProgress() self.setNormalize() self.setAlignChannels() self.setTransformation() self.setDrizzleFactor() self.setDrizzleInterpolation() self.setAutoCrop() self.setThreads() self.frameScale.set_sensitive(False) g.reference = "0" # Cancels scroll event for widget def propagateScroll(self, widget, event): Gtk.propagate_event(widget.get_parent(), event) # Disables the scroll event from some fields def disableScroll(self): mask = Gdk.EventMask.BUTTON_MOTION_MASK | Gdk.EventMask.BUTTON_PRESS_MASK | Gdk.EventMask.BUTTON_RELEASE_MASK | Gdk.EventMask.KEY_RELEASE_MASK | Gdk.EventMask.TOUCH_MASK self.builder.get_object("denoiseWidget1").set_events(mask) self.builder.get_object("denoiseWidget2").set_events(mask) self.builder.get_object("denoiseWidget3").set_events(mask) self.builder.get_object("denoiseWidget4").set_events(mask) self.builder.get_object("denoiseWidget5").set_events(mask) self.builder.get_object("radiusWidget1").set_events(mask) self.builder.get_object("radiusWidget2").set_events(mask) self.builder.get_object("radiusWidget3").set_events(mask) self.builder.get_object("radiusWidget4").set_events(mask) self.builder.get_object("radiusWidget5").set_events(mask) # Sets up a listener so that processes can communicate with each other def createListener(self, function): def listener(function): while True: try: msg = self.parentConn.recv() except: return False if (msg == "stop"): g.ui.setProgress() return False function(msg) thread = Thread(target=listener, args=(function, )) thread.start() return thread # Shows the error dialog with the given title and message def showErrorDialog(self, message): dialog = self.builder.get_object("errorDialog") dialog.format_secondary_text(message) response = dialog.run() dialog.hide() return response # Shows the warning dialog with the given title and message def showWarningDialog(self, message): dialog = self.builder.get_object("warningDialog") dialog.format_secondary_text(message) response = dialog.run() dialog.hide() return response # Opens the About dialog def showAbout(self, *args): dialog = self.builder.get_object("about") dialog.set_program_name(UI.TITLE) dialog.set_version(UI.VERSION) response = dialog.run() dialog.hide() # Opens the user manual in the default pdf application def showManual(self, *args): if sys.platform.startswith('darwin'): subprocess.call(('open', "manual/Manual.pdf")) elif os.name == 'nt': # For Windows os.startfile("manual\Manual.pdf") elif os.name == 'posix': # For Linux, Mac, etc. subprocess.call(('xdg-open', "manual/Manual.pdf")) # Disable inputs def disableUI(self): self.builder.get_object("tabs").set_sensitive(False) self.builder.get_object("toolbar").set_sensitive(False) # Enable inputs def enableUI(self): self.builder.get_object("tabs").set_sensitive(True) self.builder.get_object("toolbar").set_sensitive(True) # The following is needed to forcibly refresh the value spacing of the slider def fixFrameSliderBug(self): self.frameScale.set_value_pos(Gtk.PositionType.RIGHT) self.frameScale.set_value_pos(Gtk.PositionType.LEFT) # Sets the number of threads to use def setThreads(self, *args): def initPool(method=None): if (method == "spawn"): GLib.idle_add(self.disableUI) g.nThreads = int(self.cpus.get_value()) if (g.pool is not None): g.pool.shutdown() g.pool = ProcessPoolExecutor(g.nThreads) # This seems like the most reliable way to get the pid of pool processes self.pids = [] before = list(map(lambda p: p.pid, active_children())) g.pool.submit(dummy, ()).result() after = list(map(lambda p: p.pid, active_children())) for pid in after: if (pid not in before): self.pids.append(pid) if (method == "spawn"): GLib.idle_add(self.enableUI) # Behave a bit differently depending on platform if (get_start_method() == "spawn"): thread = Thread(target=initPool, args=(get_start_method(), )) thread.start() else: initPool() # Checks github to see if there is a new version available def checkNewVersion(self): def callUrl(): try: contents = urllib.request.urlopen( "https://api.github.com/repos/Finalfantasykid/AstraStack/releases/latest" ).read() obj = json.loads(contents) if (version.parse(obj['name']) > version.parse(UI.VERSION)): self.newVersionUrl = obj['html_url'] button.show() except: return button = self.builder.get_object("newVersion") button.hide() thread = Thread(target=callUrl, args=()) thread.start() # Opens the GitHub releases page in a browser def clickNewVersion(self, *args): webbrowser.open(self.newVersionUrl) # Checks to see if there will be enough memory to process the image def checkMemory(self, w=0, h=0): if (Sharpen.estimateMemoryUsage(w, h) > psutil.virtual_memory().available): response = self.showWarningDialog( "Your system may not have enough memory to process this file, are you sure you want to continue?" ) return (response == Gtk.ResponseType.YES) return True # Shows preview image in file chooser dialog def updatePreview(self, dialog): path = dialog.get_preview_filename() pixbuf = None try: # First try as image pixbuf = GdkPixbuf.Pixbuf.new_from_file(path) except Exception: try: # Now try as video if ("video/" in mimetypes.guess_type(path)[0]): video = Video() img = cv2.cvtColor(video.getFrame(path, 0), cv2.COLOR_BGR2RGB) height, width = img.shape[:2] z = img.tobytes() Z = GLib.Bytes.new(z) pixbuf = GdkPixbuf.Pixbuf.new_from_bytes( Z, GdkPixbuf.Colorspace.RGB, False, 8, width, height, width * 3) except Exception: dialog.set_preview_widget_active(False) if (pixbuf is not None): # Valid pixbuf maxwidth, maxheight = 250, 250 width, height = pixbuf.get_width(), pixbuf.get_height() scale = min(maxwidth / width, maxheight / height) if (scale < 1): width, height = int(width * scale), int(height * scale) pixbuf = pixbuf.scale_simple(width, height, GdkPixbuf.InterpType.BILINEAR) dialog.get_preview_widget().set_size_request( width + 10, height + 10) dialog.get_preview_widget().set_from_pixbuf(pixbuf) dialog.set_preview_widget_active(True) # Opens the file chooser to open load a file def openVideo(self, *args): self.openDialog.set_current_folder(path.expanduser("~")) self.openDialog.set_select_multiple(False) self.openDialog.set_filter(self.builder.get_object("videoFilter")) response = self.openDialog.run() self.openDialog.hide() if (response == Gtk.ResponseType.OK): try: g.file = self.openDialog.get_filename() self.video = Video() self.video.checkMemory() thread = Thread(target=self.video.run, args=()) thread.start() self.disableUI() except MemoryError as error: self.enableUI() # Opens the file chooser to open load a file def openImageSequence(self, *args): self.openDialog.set_current_folder(path.expanduser("~")) self.openDialog.set_select_multiple(True) self.openDialog.set_filter(self.builder.get_object("imageFilter")) response = self.openDialog.run() self.openDialog.hide() if (response == Gtk.ResponseType.OK): try: g.file = self.openDialog.get_filenames() self.video = Video() self.video.checkMemory() thread = Thread(target=self.video.run, args=()) thread.start() self.disableUI() except MemoryError as error: self.enableUI() # Opens the file chooser to open load a file def openImage(self, *args): self.openDialog.set_current_folder(path.expanduser("~")) self.openDialog.set_select_multiple(False) self.openDialog.set_filter(self.builder.get_object("imageFilter")) response = self.openDialog.run() self.openDialog.hide() if (response == Gtk.ResponseType.OK): self.disableUI() g.file = self.openDialog.get_filename() try: self.video = Video() img = cv2.imread(g.file) h, w = img.shape[:2] if (not self.checkMemory(w, h)): raise MemoryError() self.window.set_title(path.split(g.file)[1] + " - " + UI.TITLE) self.saveDialog.set_current_name("") self.sharpen = Sharpen(g.file, True) self.builder.get_object("alignTab").set_sensitive(False) self.builder.get_object("stackTab").set_sensitive(False) self.builder.get_object("processTab").set_sensitive(True) self.tabs.set_current_page(UI.SHARPEN_TAB) self.frame.set_from_file(g.file) except MemoryError as error: pass except: # Open Failed self.showErrorDialog( "There was an error opening the image, make sure it is a valid image." ) self.enableUI() # Opens the file chooser to save the final image def saveFileDialog(self, *args): self.saveDialog.set_current_folder(path.expanduser("~")) if (self.saveDialog.get_current_name() == ""): # Set default file to save if empty if (isinstance(g.file, list)): sList = g.file self.saveDialog.set_current_name( Path(sList[0]).stem + "_" + Path(sList[-1]).stem + ".png") else: self.saveDialog.set_current_name(Path(g.file).stem + ".png") response = self.saveDialog.run() if (response == Gtk.ResponseType.OK): fileName = self.saveDialog.get_filename() try: cv2.imwrite( fileName, cv2.cvtColor(self.sharpen.finalImage.astype('uint8'), cv2.COLOR_RGB2BGR)) except: # Save Failed self.showErrorDialog( "There was an error saving the image, make sure it is a valid file extension." ) self.saveDialog.hide() # Called when the video is finished loading def finishedVideo(self): def update(): self.tabs.next_page() self.frameScale.set_sensitive(True) self.startFrame.set_lower(0) self.startFrame.set_upper(len(self.video.frames) - 1) self.startFrame.set_value(0) self.endFrame.set_upper(len(self.video.frames) - 1) self.endFrame.set_lower(0) self.endFrame.set_value(len(self.video.frames) - 1) g.driftP1 = (0, 0) g.driftP2 = (0, 0) g.areaOfInterestP1 = (0, 0) g.areaOfInterestP2 = (0, 0) g.reference = self.video.sharpest self.frameSlider.set_value(self.video.sharpest) self.setReference() self.setStartFrame() self.setEndFrame() self.setDriftPoint() self.enableUI() if (isinstance(g.file, list)): sList = g.file self.window.set_title( path.split(sList[0])[1] + " ... " + path.split(sList[-1])[1] + " - " + UI.TITLE) else: self.window.set_title(path.split(g.file)[1] + " - " + UI.TITLE) self.saveDialog.set_current_name("") self.builder.get_object("alignTab").set_sensitive(True) self.builder.get_object("stackTab").set_sensitive(False) self.builder.get_object("processTab").set_sensitive(False) self.stack = None GLib.idle_add(update) # Called when the tab is changed. Updates parts of the UI based on the tab def changeTab(self, notebook, page, page_num, user_data=None): if (page_num == UI.LOAD_TAB or page_num == UI.ALIGN_TAB): self.frameSlider.set_value(0) self.frameSlider.set_upper(len(self.video.frames) - 1) self.setStartFrame() self.setEndFrame() self.frameScale.show() self.updateImage(None, page_num) elif (page_num == UI.STACK_TAB): self.frameSlider.set_lower(0) self.frameSlider.set_upper(len(self.align.tmats) - 1) self.frameSlider.set_value(0) self.frameScale.show() self.updateImage(None, page_num) elif (page_num == UI.SHARPEN_TAB): self.frameScale.hide() self.sharpenImage() self.fixFrameSliderBug() # Changes the image frame to the frameSlider position def updateImage(self, adjustment=None, page_num=None): if (self.video is None): return if (page_num is None): page_num = self.tabs.get_current_page() if (page_num == UI.LOAD_TAB or page_num == UI.ALIGN_TAB): videoIndex = int(self.frameSlider.get_value()) img = cv2.cvtColor( self.video.getFrame(g.file, self.video.frames[videoIndex]), cv2.COLOR_BGR2RGB) height, width = img.shape[:2] z = img.tobytes() Z = GLib.Bytes.new(z) pixbuf = GdkPixbuf.Pixbuf.new_from_bytes(Z, GdkPixbuf.Colorspace.RGB, False, 8, width, height, width * 3) self.frame.set_from_pixbuf(pixbuf) elif (page_num == UI.STACK_TAB): tmat = self.stack.tmats[int(self.frameSlider.get_value())] videoIndex = tmat[0] M = tmat[1] img = self.video.getFrame(g.file, videoIndex) if (g.autoCrop): ref = self.stack.refBG.astype(np.uint8) else: ref = None img = transform(img, ref, M, self.align.minX, self.align.maxX, self.align.minY, self.align.maxY, g.drizzleFactor, g.drizzleInterpolation) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) height, width = img.shape[:2] z = img.tobytes() Z = GLib.Bytes.new(z) pixbuf = GdkPixbuf.Pixbuf.new_from_bytes(Z, GdkPixbuf.Colorspace.RGB, False, 8, width, height, width * 3) self.frame.set_from_pixbuf(pixbuf) # Draws a rectangle where the area of interest is def drawOverlay(self, widget, cr): width = widget.get_allocated_width() height = widget.get_allocated_height() def drawPoint(cr, x, y): cr.new_sub_path() cr.set_line_width(2) cr.set_source_rgb(1, 1, 1) cr.arc(x, y, 2, 0, 2 * math.pi) cr.stroke_preserve() cr.set_source_rgb(1, 0, 0) cr.fill() def drawRect(cr, x1, y1, x2, y2): cr.rectangle(0, 0, x1, y1) cr.rectangle(0, y1, x1, (y2 - y1)) cr.rectangle(0, y1, x1, height * 2) cr.rectangle(x1, y2, (x2 - x1), height * 2) cr.rectangle(x2, y2, width * 2, height * 2) cr.rectangle(x2, y1, width * 2, (y2 - y1)) cr.rectangle(x2, 0, width * 2, y1) cr.rectangle(x1, 0, (x2 - x1), y1) cr.set_source_rgba(0, 0, 0, 0.25) cr.fill() cr.set_line_width(1) cr.set_source_rgb(1, 0, 0) cr.rectangle(x1, y1, (x2 - x1), (y2 - y1)) cr.stroke() if (self.tabs.get_current_page() == UI.ALIGN_TAB): current = self.frameSlider.get_value() # Area of Interest px1 = min(g.areaOfInterestP1[0], g.areaOfInterestP2[0]) py1 = min(g.areaOfInterestP1[1], g.areaOfInterestP2[1]) px2 = max(g.areaOfInterestP1[0], g.areaOfInterestP2[0]) py2 = max(g.areaOfInterestP1[1], g.areaOfInterestP2[1]) # Drift Points dx1 = g.driftP1[0] dy1 = g.driftP1[1] dx2 = g.driftP2[0] dy2 = g.driftP2[1] dx = 0 dy = 0 if (dx1 != 0 and dy1 != 0 and dx2 != 0 and dy2 != 0): dx = dx2 - dx1 dy = dy2 - dy1 if (px1 != 0 and py1 != 0 and px2 != 0 and py2 != 0): # Draw Area of Interest Rectangle drawRect( cr, px1 + (dx / (g.endFrame - g.startFrame)) * (current - g.startFrame), py1 + (dy / (g.endFrame - g.startFrame)) * (current - g.startFrame), px2 + (dx / (g.endFrame - g.startFrame)) * (current - g.startFrame), py2 + (dy / (g.endFrame - g.startFrame)) * (current - g.startFrame)) if (dx1 != 0 and dy1 != 0 and current == g.startFrame): # Draw point on first frame drawPoint(cr, dx1, dy1) if (dx1 != 0 and dy1 != 0 and current != g.startFrame and dx2 != 0 and dy2 != 0 and current != g.endFrame): # Draw interpolated point drawPoint( cr, dx1 + (dx / (g.endFrame - g.startFrame)) * (current - g.startFrame), dy1 + (dy / (g.endFrame - g.startFrame)) * (current - g.startFrame)) if (dx2 != 0 and dy2 != 0 and current == g.endFrame): # Draw point on last frame drawPoint(cr, dx2, dy2) # Sets the reference frame to the current visible frame def setReference(self, *args): g.reference = str(int(self.frameSlider.get_value())) self.builder.get_object("referenceLabel").set_text(g.reference) self.builder.get_object("alignButton").set_sensitive(True) # Updates the progress bar def setProgress(self, i=0, total=0, text=""): def update(): if (total == 0): self.progressBox.hide() else: self.progressBox.show() self.progress.set_fraction(i / total) self.progress.set_text(text + " " + str(round((i / total) * 100)) + "%") GLib.idle_add(update) # Sets the start frame for trimming def setStartFrame(self, *args): g.startFrame = int(self.startFrame.get_value()) self.endFrame.set_lower(g.startFrame + 1) self.frameSlider.set_lower(g.startFrame) self.frameSlider.set_value( max(g.startFrame, self.frameSlider.get_value())) if (int(g.startFrame) > int(g.reference)): # Reference is outside of the range, fix it g.reference = str(int(g.startFrame)) self.builder.get_object("referenceLabel").set_text(g.reference) self.fixFrameSliderBug() # Sets the end frame for trimming def setEndFrame(self, *args): g.endFrame = int(self.endFrame.get_value()) self.startFrame.set_upper(g.endFrame - 1) self.frameSlider.set_upper(g.endFrame) self.frameSlider.set_value( min(g.endFrame, self.frameSlider.get_value())) if (int(g.endFrame) < int(g.reference)): # Reference is outside of the range, fix it g.reference = str(int(g.endFrame)) self.builder.get_object("referenceLabel").set_text(g.reference) self.fixFrameSliderBug() # Drift Point 1 Button Clicked def clickDriftP1(self, *args): self.clickedDriftP1 = False self.clickedDriftP2 = False self.clickedAreaOfInterest = False self.setDriftPoint() self.frameSlider.set_value(g.startFrame) self.clickedDriftP1 = True self.window.get_window().set_cursor( Gdk.Cursor(Gdk.CursorType.CROSSHAIR)) # Drift Point 2 Button Clicked def clickDriftP2(self, *args): self.clickedDriftP1 = False self.clickedDriftP2 = False self.clickedAreaOfInterest = False self.setDriftPoint() self.frameSlider.set_value(g.endFrame) self.clickedDriftP2 = True self.window.get_window().set_cursor( Gdk.Cursor(Gdk.CursorType.CROSSHAIR)) # Reset Drift Point 1 to (0, 0) def resetDriftP1(self, widget, event): if (event.button == 3): # Right Click g.driftP1 = (0, 0) self.clickedDriftP1 = False self.clickedDriftP2 = False self.clickedAreaOfInterest = False self.window.get_window().set_cursor( Gdk.Cursor(Gdk.CursorType.LEFT_PTR)) self.overlay.queue_draw() # Reset Drift Point 2 to (0, 0) def resetDriftP2(self, widget, event): if (event.button == 3): # Right Click g.driftP2 = (0, 0) self.clickedDriftP1 = False self.clickedDriftP2 = False self.clickedAreaOfInterest = False self.window.get_window().set_cursor( Gdk.Cursor(Gdk.CursorType.LEFT_PTR)) self.overlay.queue_draw() # Updates the drift point def setDriftPoint(self, *args): if (self.clickedDriftP1 or self.clickedDriftP2): if (self.clickedDriftP1): g.driftP1 = self.mousePosition elif (self.clickedDriftP2): g.driftP2 = self.mousePosition self.clickedDriftP1 = False self.clickedDriftP2 = False self.window.get_window().set_cursor( Gdk.Cursor(Gdk.CursorType.LEFT_PTR)) self.overlay.queue_draw() # Area of Interest button clicked def clickAreaOfInterest(self, *args): g.areaOfInterestP1 = (0, 0) g.areaOfInterestP2 = (0, 0) self.clickedDriftP1 = False self.clickedDriftP2 = False self.clickedAreaOfInterest = True self.frameSlider.set_value(g.startFrame) self.window.get_window().set_cursor( Gdk.Cursor(Gdk.CursorType.CROSSHAIR)) self.overlay.queue_draw() # Reset Area of Interest to (0, 0) def resetAreaOfInterest(self, widget, event): if (event.button == 3): # Right Click g.areaOfInterestP1 = (0, 0) g.areaOfInterestP2 = (0, 0) self.clickedDriftP1 = False self.clickedDriftP2 = False self.clickedAreaOfInterest = False self.window.get_window().set_cursor( Gdk.Cursor(Gdk.CursorType.LEFT_PTR)) self.overlay.queue_draw() # First point int the Area of Interest clicked, drag started def dragBegin(self, *args): if (self.clickedAreaOfInterest): g.areaOfInterestP1 = self.mousePosition # Mouse released after dragging Area of Interest def dragEnd(self, *args): if (self.clickedAreaOfInterest): g.areaOfInterestP2 = self.mousePosition self.clickedAreaOfInterest = False self.window.get_window().set_cursor( Gdk.Cursor(Gdk.CursorType.LEFT_PTR)) # Called when the mouse moves over the frame def updateMousePosition(self, *args): pointer = self.frame.get_pointer() self.mousePosition = (min(max(0, pointer.x), self.frame.get_allocation().width), min(max(0, pointer.y), self.frame.get_allocation().height)) if (self.clickedAreaOfInterest): if (g.areaOfInterestP1 != (0, 0)): g.areaOfInterestP2 = self.mousePosition self.overlay.queue_draw() # Sets whether or not to normalize the frames during alignment def setNormalize(self, *args): g.normalize = self.normalize.get_active() # Sets whether or not to align channels separately def setAlignChannels(self, *args): g.alignChannels = self.alignChannels.get_active() # Sets the type of transformation def setTransformation(self, *args): text = self.transformation.get_active_text() if (text == "None"): g.transformation = -1 elif (text == "Translation"): g.transformation = StackReg.TRANSLATION elif (text == "Rigid Body"): g.transformation = StackReg.RIGID_BODY elif (text == "Scaled Rotation"): g.transformation = StackReg.SCALED_ROTATION elif (text == "Affine"): g.transformation = StackReg.AFFINE # Sets the drizzle scaling factor def setDrizzleFactor(self, *args): text = self.drizzleFactor.get_active_text() if (text == "0.25X"): g.drizzleFactor = 0.25 elif (text == "0.50X"): g.drizzleFactor = 0.50 elif (text == "0.75X"): g.drizzleFactor = 0.75 elif (text == "1.0X"): g.drizzleFactor = 1.0 elif (text == "1.5X"): g.drizzleFactor = 1.5 elif (text == "2.0X"): g.drizzleFactor = 2.0 elif (text == "2.5X"): g.drizzleFactor = 2.5 elif (text == "3.0X"): g.drizzleFactor = 3.0 if (self.stack is not None): self.stack.generateRefBG() self.updateImage() # Sets the drizzle scaling factor def setDrizzleInterpolation(self, *args): text = self.drizzleInterpolation.get_active_text() if (text == "Nearest Neighbor"): g.drizzleInterpolation = cv2.INTER_NEAREST elif (text == "Bilinear"): g.drizzleInterpolation = cv2.INTER_LINEAR elif (text == "Bicubic"): g.drizzleInterpolation = cv2.INTER_CUBIC elif (text == "Lanczos"): g.drizzleInterpolation = cv2.INTER_LANCZOS4 if (self.stack is not None): self.stack.generateRefBG() self.updateImage() # Sets whether or not to auto crop def setAutoCrop(self, *args): g.autoCrop = not self.autoCrop.get_active() self.updateImage() # Runs the Alignment step def clickAlign(self, *args): self.align = Align(self.video.frames[g.startFrame:g.endFrame + 1]) thread = Thread(target=self.align.run, args=()) thread.start() self.disableUI() # Kills all pool processes def killPool(self): for pid in self.pids: if (psutil.pid_exists(pid)): p = psutil.Process(pid) p.kill() # Stops the current action being performed def stopProcessing(self, *args): self.killPool() g.pool = None self.setThreads() self.setProgress() self.enableUI() # Called when the Alignment is complete def finishedAlign(self): def update(): self.stack = Stack(self.align.tmats) self.tabs.next_page() self.enableUI() self.builder.get_object("alignTab").set_sensitive(True) self.builder.get_object("stackTab").set_sensitive(True) self.builder.get_object("processTab").set_sensitive(False) self.limit.set_upper(len(self.align.tmats)) self.limit.set_value(int(len(self.align.tmats) / 2)) self.limitPercent.set_value( round(self.limit.get_value() / len(self.align.tmats) * 100)) self.setLimit() self.setLimitPercent() GLib.idle_add(update) # Sets the number of frames to use in the Stack def setLimit(self, *args): self.limitPercent.disconnect(self.limitPercentSignal) self.limit.set_upper(len(self.align.tmats)) g.limit = int(self.limit.get_value()) self.limitPercent.set_value( round(g.limit / len(self.align.tmats) * 100)) self.limitPercentSignal = self.limitPercent.connect( "value-changed", self.setLimitPercent) # Sets the number of frames to use in the Stack def setLimitPercent(self, *args): limitPercent = self.limitPercent.get_value() / 100 self.limit.set_value(round(limitPercent * len(self.align.tmats))) # Stack Button clicked def clickStack(self, *args): try: self.stack.checkMemory() thread = Thread(target=self.stack.run, args=()) thread.start() self.disableUI() except MemoryError as error: self.enableUI() # Called when the stack is complete def finishedStack(self): def update(): self.sharpen = Sharpen(self.stack.stackedImage) self.tabs.next_page() self.enableUI() self.builder.get_object("alignTab").set_sensitive(True) self.builder.get_object("stackTab").set_sensitive(True) self.builder.get_object("processTab").set_sensitive(True) GLib.idle_add(update) # Sharpens the final Stacked image def sharpenImage(self, *args): g.sharpen1 = self.builder.get_object("sharpen1").get_value() g.sharpen2 = self.builder.get_object("sharpen2").get_value() g.sharpen3 = self.builder.get_object("sharpen3").get_value() g.sharpen4 = self.builder.get_object("sharpen4").get_value() g.sharpen5 = self.builder.get_object("sharpen5").get_value() g.radius1 = self.builder.get_object("radius1").get_value() g.radius2 = self.builder.get_object("radius2").get_value() g.radius3 = self.builder.get_object("radius3").get_value() g.radius4 = self.builder.get_object("radius4").get_value() g.radius5 = self.builder.get_object("radius5").get_value() g.denoise1 = self.builder.get_object("denoise1").get_value() g.denoise2 = self.builder.get_object("denoise2").get_value() g.denoise3 = self.builder.get_object("denoise3").get_value() g.denoise4 = self.builder.get_object("denoise4").get_value() g.denoise5 = self.builder.get_object("denoise5").get_value() g.level1 = self.builder.get_object("level1").get_active() g.level2 = self.builder.get_object("level2").get_active() g.level3 = self.builder.get_object("level3").get_active() g.level4 = self.builder.get_object("level4").get_active() g.level5 = self.builder.get_object("level5").get_active() g.gamma = self.builder.get_object("gammaAdjust").get_value() g.blackLevel = self.builder.get_object("blackLevelAdjust").get_value() g.value = self.builder.get_object("valueAdjust").get_value() g.redAdjust = self.builder.get_object("redAdjust").get_value() g.greenAdjust = self.builder.get_object("greenAdjust").get_value() g.blueAdjust = self.builder.get_object("blueAdjust").get_value() g.saturation = self.builder.get_object("saturationAdjust").get_value() if (len(args) > 0 and (self.builder.get_object("gammaAdjust") == args[0] or self.builder.get_object("blackLevelAdjust") == args[0] or self.builder.get_object("redAdjust") == args[0] or self.builder.get_object("greenAdjust") == args[0] or self.builder.get_object("blueAdjust") == args[0] or self.builder.get_object("saturationAdjust") == args[0] or self.builder.get_object("valueAdjust") == args[0])): processAgain = self.sharpen.processAgain processColor = True else: processAgain = True processColor = False if (self.sharpen is None): if (self.stack is not None): self.sharpen = Sharpen(self.stack.stackedImage) else: self.sharpen = Sharpen(g.file, True) if (self.processThread != None and self.processThread.is_alive()): self.sharpen.processAgain = processAgain self.sharpen.processColorAgain = processColor else: self.processThread = Thread(target=self.sharpen.run, args=(processAgain, processColor)) self.processThread.start() # Called when sharpening is complete def finishedSharpening(self): def update(): z = self.sharpen.finalImage.astype('uint8').tobytes() Z = GLib.Bytes.new(z) pixbuf = GdkPixbuf.Pixbuf.new_from_bytes(Z, GdkPixbuf.Colorspace.RGB, False, 8, self.sharpen.w, self.sharpen.h, self.sharpen.w * 3) self.frame.set_from_pixbuf(pixbuf) GLib.idle_add(update) # Closes the application def close(self, *args): self.killPool() Gtk.main_quit() sys.exit()
def sortStack(stack): temp_stack = Stack() temp_stack.push(stack.pop()) #pop an element off and hold in a variable #peek at element in temp_stack #if greater, just push on top #if less, keep popping until you reach smaller element (use peek) #insert temp element #push rest back on while not stack.isEmpty(): value = stack.pop() while temp_stack.peek() > value or not temp_stack.isEmpty(): stack.push(temp_stack.pop()) temp_stack.push(value) while not temp_stack.isEmpty(): stack.push(temp_stack.pop()) return stack
def divOp(): stack.div() operation = { 'pop': popOp, 'add': addOp, 'sub': subOp, 'mul': mulOp, 'div': divOp, } with open("entrada.txt", "r") as textFile: stack = Stack() pushOp = False for line in textFile: for word in line.split(): if pushOp: stack.push(word) pushOp = False elif word == "push": pushOp = True else: try:
class DSQTester(unittest.TestCase): def setUp(self): self.__deque = get_deque() self.__stack = Stack() self.__queue = Queue() def test_empty_LL_deque_string(self): self.assertEqual('[ ]', str(self.__deque), 'Empty deque should print as "[ ]"') def test_empty_LL_deque_push_front(self): self.__deque.push_front(1) self.assertEqual('[ 1 ]', str(self.__deque)) def test_empty_LL_deque_push_back(self): self.__deque.push_back(1) self.assertEqual('[ 1 ]', str(self.__deque)) def test_empty_LL_deque_pop_front_return(self):#tests if pop method returns correctly, should return None. returned = self.__deque.pop_front() self.assertEqual(None, returned) def test_empty_LL_deque_pop_back_return(self): returned = self.__deque.pop_back() self.assertEqual(None, returned) def test_empty_LL_deque_pop_front(self):#tests if pop method works correctly when the deque is empty. self.__deque.pop_front() self.assertEqual('[ ]', str(self.__deque)) def test_empty_LL_deque_pop_back(self): self.__deque.pop_back() self.assertEqual('[ ]', str(self.__deque)) def test_empty_LL_deque_peek_front(self): returned = self.__deque.peek_front() self.assertEqual(None, returned) def test_empty_LL_deque_peek_back(self): returned = self.__deque.peek_back() self.assertEqual(None, returned) def test_empty_LL_deque_len(self): self.assertEqual(0, len(self.__deque)) def test_one_LL_deque_string(self):#same testing for a deque of size 1. self.__deque.push_front(1) self.assertEqual('[ 1 ]', str(self.__deque)) def test_one_LL_deque_push_front(self): self.__deque.push_front(1) self.__deque.push_front(2) self.assertEqual('[ 2, 1 ]', str(self.__deque)) def test_one_LL_deque_push_back(self): self.__deque.push_back(1) self.__deque.push_back(2) self.assertEqual('[ 1, 2 ]', str(self.__deque)) def test_one_LL_deque_pop_front_return(self):#tests if pop method returns correctly. self.__deque.push_front(1) returned = self.__deque.pop_front() self.assertEqual(1, returned) def test_one_LL_deque_pop_back_return(self): self.__deque.push_front(1) returned = self.__deque.pop_back() self.assertEqual(1, returned) def test_one_LL_deque_pop_front(self):#tests if pop method removes correctly. self.__deque.push_front(1) self.__deque.pop_front() self.assertEqual('[ ]', str(self.__deque)) def test_one_LL_deque_pop_back(self): self.__deque.push_front(1) self.__deque.pop_back() self.assertEqual('[ ]', str(self.__deque)) def test_one_LL_deque_peek_front(self): self.__deque.push_front(1) returned = self.__deque.peek_front() self.assertEqual(1, returned) def test_one_LL_deque_peek_back(self): self.__deque.push_front(1) returned = self.__deque.peek_back() self.assertEqual(1, returned) def test_one_LL_deque_len(self): self.__deque.push_front(1) self.assertEqual(1, len(self.__deque)) def test_two_LL_deque_string(self):#same tests for a deque with size 2. self.__deque.push_front(1) self.__deque.push_front(2) self.assertEqual('[ 2, 1 ]', str(self.__deque)) def test_two_LL_deque_push_front(self): self.__deque.push_front(1) self.__deque.push_front(2) self.__deque.push_front(3) self.assertEqual('[ 3, 2, 1 ]', str(self.__deque)) def test_two_LL_deque_push_back(self): self.__deque.push_back(1) self.__deque.push_back(2) self.__deque.push_back(3) self.assertEqual('[ 1, 2, 3 ]', str(self.__deque)) def test_two_LL_deque_pop_front_return(self):#tests if pop method returns correctly. self.__deque.push_front(1) self.__deque.push_front(2) returned = self.__deque.pop_front() self.assertEqual(2, returned) def test_two_LL_deque_pop_back_return(self): self.__deque.push_front(1) self.__deque.push_front(2) returned = self.__deque.pop_back() self.assertEqual(1, returned) def test_two_LL_deque_pop_front(self):#tests if pop method removes correctly. self.__deque.push_front(1) self.__deque.push_front(2) self.__deque.pop_front() self.assertEqual('[ 1 ]', str(self.__deque)) def test_two_LL_deque_pop_back(self): self.__deque.push_front(1) self.__deque.push_front(2) self.__deque.pop_back() self.assertEqual('[ 2 ]', str(self.__deque)) def test_two_LL_deque_peek_front(self): self.__deque.push_front(1) self.__deque.push_front(2) returned = self.__deque.peek_front() self.assertEqual(2, returned) def test_two_LL_deque_peek_back(self): self.__deque.push_front(1) self.__deque.push_front(2) returned = self.__deque.peek_back() self.assertEqual(1, returned) def test_two_LL_deque_len(self): self.__deque.push_front(1) self.__deque.push_front(2) self.assertEqual(2, len(self.__deque)) def test_LL_deque_push_pop(self):#test if multiple push and pop work correctly self.__deque.push_front(1) self.__deque.push_front(2) self.__deque.push_back(2) self.__deque.pop_back() self.__deque.push_front(3) self.__deque.pop_front() self.assertEqual('[ 2, 1 ]', str(self.__deque)) def test_empty_ARR_deque_string(self): self.__deque = get_deque(1) self.assertEqual('[ ]', str(self.__deque), 'Empty deque should print as "[ ]"') def test_empty_ARR_deque_push_front(self): self.__deque = get_deque(1) self.__deque.push_front(1) self.assertEqual('[ 1 ]', str(self.__deque)) def test_empty_ARR_deque_push_back(self): self.__deque = get_deque(1) self.__deque.push_back(1) self.assertEqual('[ 1 ]', str(self.__deque)) def test_empty_ARR_deque_pop_front_return(self):#tests if pop method returns correctly, should return None. self.__deque = get_deque(1) returned = self.__deque.pop_front() self.assertEqual(None, returned) def test_empty_ARR_deque_pop_back_return(self): self.__deque = get_deque(1) returned = self.__deque.pop_back() self.assertEqual(None, returned) def test_empty_ARR_deque_pop_front(self):#tests if pop method works correctly when the deque is empty. self.__deque = get_deque(1) self.__deque.pop_front() self.assertEqual('[ ]', str(self.__deque)) def test_empty_ARR_deque_pop_back(self): self.__deque = get_deque(1) self.__deque.pop_back() self.assertEqual('[ ]', str(self.__deque)) def test_empty_ARR_deque_peek_front(self): self.__deque = get_deque(1) returned = self.__deque.peek_front() self.assertEqual(None, returned) def test_empty_ARR_deque_peek_back(self): self.__deque = get_deque(1) returned = self.__deque.peek_back() self.assertEqual(None, returned) def test_empty_ARR_deque_len(self): self.__deque = get_deque(1) self.assertEqual(0, len(self.__deque)) def test_one_ARR_deque_string(self):#same testing for a deque of size 1. self.__deque = get_deque(1) self.__deque.push_front(1) self.assertEqual('[ 1 ]', str(self.__deque)) def test_one_ARR_deque_push_front(self):#also tests if __grow works self.__deque = get_deque(1) self.__deque.push_front(1) self.__deque.push_front(2) self.assertEqual('[ 2, 1 ]', str(self.__deque)) def test_one_ARR_deque_push_back(self):#also tests if __grow works self.__deque = get_deque(1) self.__deque.push_back(1) self.__deque.push_back(2) self.assertEqual('[ 1, 2 ]', str(self.__deque)) def test_one_ARR_deque_pop_front_return(self):#tests if pop method returns correctly. self.__deque = get_deque(1) self.__deque.push_front(1) returned = self.__deque.pop_front() self.assertEqual(1, returned) def test_one_ARR_deque_pop_back_return(self): self.__deque = get_deque(1) self.__deque.push_front(1) returned = self.__deque.pop_back() self.assertEqual(1, returned) def test_one_ARR_deque_pop_front(self):#tests if pop method removes correctly. self.__deque = get_deque(1) self.__deque.push_front(1) self.__deque.pop_front() self.assertEqual('[ ]', str(self.__deque)) def test_one_ARR_deque_pop_back(self): self.__deque = get_deque(1) self.__deque.push_front(1) self.__deque.pop_back() self.assertEqual('[ ]', str(self.__deque)) def test_one_ARR_deque_peek_front(self): self.__deque = get_deque(1) self.__deque.push_front(1) returned = self.__deque.peek_front() self.assertEqual(1, returned) def test_one_ARR_deque_peek_back(self): self.__deque = get_deque(1) self.__deque.push_front(1) returned = self.__deque.peek_back() self.assertEqual(1, returned) def test_one_ARR_deque_len(self): self.__deque = get_deque(1) self.__deque.push_front(1) self.assertEqual(1, len(self.__deque)) def test_two_ARR_deque_string(self):#same tests for a deque with size 2. self.__deque = get_deque(1) self.__deque.push_front(1) self.__deque.push_front(2) self.assertEqual('[ 2, 1 ]', str(self.__deque)) def test_two_ARR_deque_push_front(self): self.__deque = get_deque(1) self.__deque.push_front(1) self.__deque.push_front(2) self.__deque.push_front(3) self.assertEqual('[ 3, 2, 1 ]', str(self.__deque)) def test_two_ARR_deque_push_back(self): self.__deque = get_deque(1) self.__deque.push_back(1) self.__deque.push_back(2) self.__deque.push_back(3) self.assertEqual('[ 1, 2, 3 ]', str(self.__deque)) def test_two_ARR_deque_pop_front_return(self):#tests if pop method returns correctly. self.__deque = get_deque(1) self.__deque.push_front(1) self.__deque.push_front(2) returned = self.__deque.pop_front() self.assertEqual(2, returned) def test_two_ARR_deque_pop_back_return(self): self.__deque = get_deque(1) self.__deque.push_front(1) self.__deque.push_front(2) returned = self.__deque.pop_back() self.assertEqual(1, returned) def test_two_ARR_deque_pop_front(self):#tests if pop method removes correctly. self.__deque = get_deque(1) self.__deque.push_front(1) self.__deque.push_front(2) self.__deque.pop_front() self.assertEqual('[ 1 ]', str(self.__deque)) def test_two_ARR_deque_pop_back(self): self.__deque = get_deque(1) self.__deque.push_front(1) self.__deque.push_front(2) self.__deque.pop_back() self.assertEqual('[ 2 ]', str(self.__deque)) def test_two_ARR_deque_peek_front(self): self.__deque = get_deque(1) self.__deque.push_front(1) self.__deque.push_front(2) returned = self.__deque.peek_front() self.assertEqual(2, returned) def test_two_ARR_deque_peek_back(self): self.__deque = get_deque(1) self.__deque.push_front(1) self.__deque.push_front(2) returned = self.__deque.peek_back() self.assertEqual(1, returned) def test_two_ARR_deque_len(self): self.__deque = get_deque(1) self.__deque.push_front(1) self.__deque.push_front(2) self.assertEqual(2, len(self.__deque)) def test_ARR_deque_push_pop(self):#test if multiple push and pops work expectedly self.__deque = get_deque(1) self.__deque.push_front(1) self.__deque.push_front(2) self.__deque.push_back(2) self.__deque.pop_back() self.__deque.push_front(3) self.__deque.pop_front() self.assertEqual('[ 2, 1 ]', str(self.__deque)) def test_ARR_deque_push_front_circularity(self):#tests push_front when front index is 0. self.__deque = get_deque(1) self.__deque.push_front(1) self.__deque.push_front(2) self.__deque.push_front(3) self.assertEqual('[ 3, 2, 1 ]', str(self.__deque)) def test_ARR_deque_push_back_circularity(self):#similarly,tests if circular array works self.__deque = get_deque(1) self.__deque.push_back(1) self.__deque.push_back(2) self.__deque.push_back(3) self.assertEqual('[ 1, 2, 3 ]', str(self.__deque)) def test_ARR_deque_pop_front_circularity(self):#tests pop_front when front index is capacity-1. self.__deque = get_deque(1) self.__deque.push_front(1) self.__deque.push_front(2) self.__deque.pop_front() self.assertEqual('[ 1 ]', str(self.__deque)) def test_ARR_deque_pop_back_circularity(self):#tests pop_back when back index is 0. self.__deque = get_deque(1) self.__deque.push_front(1) self.__deque.push_front(2) self.__deque.pop_back() self.assertEqual('[ 2 ]', str(self.__deque)) def test_empty_stack_str(self): self.assertEqual('[ ]', str(self.__stack)) def test_empty_stack_len(self): self.assertEqual(0, len(self.__stack)) def test_empty_stack_push(self): self.__stack.push(1) self.assertEqual('[ 1 ]', str(self.__stack)) def test_empty_stack_pop_return(self):#tests if pop returns value correctly self.assertEqual(None, self.__stack.pop()) def test_empty_stack_pop_remove(self):#tests if pop removes value correctly self.__stack.pop() self.assertEqual('[ ]', str(self.__stack)) def test_empty_stack_peek(self): self.assertEqual(None, self.__stack.peek()) def test_one_stack_str(self): self.__stack.push(1) self.assertEqual('[ 1 ]', str(self.__stack)) def test_one_stack_len(self): self.__stack.push(1) self.assertEqual(1, len(self.__stack)) def test_one_stack_push(self):#notice that the top of stack is the at back of the deque, so the printed string from left to right is from bottom to top. self.__stack.push(1) self.__stack.push(2) self.assertEqual('[ 1, 2 ]', str(self.__stack)) def test_one_stack_pop_return(self):#tests if pop returns value correctly self.__stack.push(1) self.assertEqual(1, self.__stack.pop()) def test_one_stack_pop_remove(self):#tests if pop removes value correctly self.__stack.push(1) self.__stack.pop() self.assertEqual('[ ]', str(self.__stack)) def test_one_stack_peek(self): self.__stack.push(1) self.assertEqual(1, self.__stack.peek()) def test_two_stack_str(self):#notice that the top of stack is the at back of the deque self.__stack.push(1) self.__stack.push(2) self.assertEqual('[ 1, 2 ]', str(self.__stack)) def test_two_stack_len(self): self.__stack.push(1) self.__stack.push(2) self.assertEqual(2, len(self.__stack)) def test_two_stack_push(self):#notice that the top of stack is the at back of the deque self.__stack.push(1) self.__stack.push(2) self.__stack.push(3) self.assertEqual('[ 1, 2, 3 ]', str(self.__stack)) def test_two_stack_pop_return(self):#tests if pop returns value correctly self.__stack.push(1) self.__stack.push(2) self.assertEqual(2, self.__stack.pop()) def test_two_stack_pop_remove(self):#tests if pop removes value correctly self.__stack.push(1) self.__stack.push(2) self.__stack.pop() self.assertEqual('[ 1 ]', str(self.__stack)) def test_two_stack_peek(self): self.__stack.push(1) self.__stack.push(2) self.assertEqual(2, self.__stack.peek()) def test_stack_multiple_push_pop(self):#test if multiple push and pops work as expected self.__stack.push(1) self.__stack.push(2) self.__stack.pop() self.__stack.push(4) self.__stack.pop() self.__stack.push(6) self.__stack.push(7) self.__stack.push(8) self.__stack.pop() self.assertEqual('[ 1, 6, 7 ]', str(self.__stack)) def test_empty_queue_str(self): self.assertEqual('[ ]', str(self.__queue)) def test_empty_queue_len(self): self.assertEqual(0, len(self.__queue)) def test_empty_queue_enqueue(self): self.__queue.enqueue(1) self.assertEqual('[ 1 ]', str(self.__queue)) def test_empty_queue_dequeue_return(self):#tests if dequeue returns value correctly self.assertEqual(None, self.__queue.dequeue()) def test_empty_queue_dequeue_remove(self):#tests if dequeue removes value correctly self.__queue.dequeue() self.assertEqual('[ ]', str(self.__queue)) def test_empty_queue_peek(self): self.assertEqual(None, self.__queue.peek()) def test_one_queue_str(self): self.__queue.enqueue(1) self.assertEqual('[ 1 ]', str(self.__queue)) def test_one_queue_len(self): self.__queue.enqueue(1) self.assertEqual(1, len(self.__queue)) def test_one_queue_enqueue(self):#notice that the right end of string representation is the back of queue. self.__queue.enqueue(1) self.__queue.enqueue(2) self.assertEqual('[ 1, 2 ]', str(self.__queue)) def test_one_queue_dequeue_return(self):#tests if dequeue returns value correctly self.__queue.enqueue(1) self.assertEqual(1, self.__queue.dequeue()) def test_one_queue_dequeue_remove(self):#tests if dequeue removes value correctly self.__queue.enqueue(1) self.__queue.dequeue() self.assertEqual('[ ]', str(self.__queue)) def test_one_queue_peek(self): self.__queue.enqueue(1) self.assertEqual(1, self.__queue.peek()) def test_two_queue_str(self): self.__queue.enqueue(1) self.__queue.enqueue(2) self.assertEqual('[ 1, 2 ]', str(self.__queue)) def test_two_queue_len(self): self.__queue.enqueue(1) self.__queue.enqueue(2) self.assertEqual(2, len(self.__queue)) def test_two_queue_enqueue(self):#notice that the right end of string representation is the back of queue. self.__queue.enqueue(1) self.__queue.enqueue(2) self.__queue.enqueue(3) self.assertEqual('[ 1, 2, 3 ]', str(self.__queue)) def test_two_queue_dequeue_return(self):#tests if dequeue returns value correctly self.__queue.enqueue(1) self.__queue.enqueue(2) self.assertEqual(1, self.__queue.dequeue()) def test_two_queue_dequeue_remove(self):#tests if dequeue removes value correctly self.__queue.enqueue(1) self.__queue.enqueue(2) self.__queue.dequeue() self.assertEqual('[ 2 ]', str(self.__queue)) def test_two_queue_peek(self): self.__queue.enqueue(1) self.__queue.enqueue(2) self.assertEqual(1, self.__queue.peek()) def test_queue_multiple_enqueue_dequeue(self):#test if multiple enqueues and dequeues work as expected self.__queue.enqueue(1) self.__queue.enqueue(2) self.__queue.dequeue() self.__queue.enqueue(4) self.__queue.dequeue() self.__queue.enqueue(6) self.__queue.enqueue(7) self.__queue.enqueue(8) self.__queue.dequeue() self.assertEqual('[ 6, 7, 8 ]', str(self.__queue))
def evalPost(post_list): val_stack = Stack() for post in post_list: # Numbers into a value stack if type(post) is float: val_stack.push(post) # Operators # calculate two numbers then add new value to the value stack elif post == '+': n1 = val_stack.pop() n2 = val_stack.pop() val_stack.push(n2 + n1) elif post == '-': n1 = val_stack.pop() n2 = val_stack.pop() val_stack.push(n2 - n1) elif post == '*': n1 = val_stack.pop() n2 = val_stack.pop() val_stack.push(n2 * n1) elif post == '/': n1 = val_stack.pop() n2 = val_stack.pop() val_stack.push(float(n2 / n1)) # Get the final value after calculating all return val_stack.pop()
class Trashcan: def __init__(self, rounds): self.rounds = rounds self.player_1_round = 10 # A counter to keep track of which round each person is on self.player_2_round = 10 self.draw_pile = Stack() self.burn_pile = Stack() self.player_1_hand = Queue() self.player_2_hand = Queue() self.cards = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] # Standard suit of cards self.cards_s = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"] self.card_names = [ "Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King" ] # card name equivalents self.player_1_field = [] self.player_2_field = [] def create_draw_pile(self): # This code was reused from War.py """ Adds cards to dealing pile :return: None """ for i in range(4): for l in self.cards: self.draw_pile.push(l) self.draw_pile.shuffle() def draw(self, hand): """ Takes a card from the top of the draw_pile and enqueues that card into the the provided player's hand :param hand: A queue for a player's cards held in their hand :return: None """ card = self.draw_pile.pop() hand.enqueue(card) def create_playing_field( self, n, hand, field): # This is the code I did BigO analysis for """ Draws 10 cards to each player from the draw_pile. Then the playing fields get the cards from each players hand :return: None """ while hand.size() < n: self.draw(hand) while hand.size() != 0: field.append(hand.dequeue()) def placing_phase(self, hand, field, player_round): """ Draws a card and places it in the appropriate spot. If a King is drawn, prompts the user to provide a slot to place it in. If a Jack or Queen is drawn, the cycle ends. If a drawn card can not be placed, the cycle ends. :param hand: The hand of the current player :param field: The field of the current player :param player_round: what round the player is on :return: None """ if self.draw_pile.size( ) == 0: # If the draw pile is empty, it is refreshed using the burn pile self.refresh() self.draw(hand) while True: card = hand.dequeue() if card == 0 or card == 7: # Code to print out what was drawn using an if the card is an Ace or 8 input("An " + self.card_names[card] + " was drawn.") else: # Code to print out what was drawn for all other cards input("A " + self.card_names[card] + " was drawn.") if player_round <= card < 12: # If the card is a Jack or Queen print("Nothing could be done. . .") break elif card == 12 or card == "King": # If the card is a King print( "Here is your current field:" ) # Just a reminder to the player of what they have so far. print(field) choice = input( "Choose a number between 1 and 10 to place the king in that spot." ) # Asks where the user wants the King while True: while choice not in self.cards_s: print("That was an invalid choice.") choice = input( "Choose a number between 1 and 10 to place the king in that spot" ) choice = int(choice) if isinstance( field[choice - 1], str ): # Checks to see if the slot has been filled by checking if the type is a string choice = input( "That spot has already been filled with the correct card. Please provide " "another number") else: hand.enqueue(field[choice - 1]) # Fills the slot with a King field[choice - 1] = "King" break elif field[ card] == "King": # Checks to see if the slot has a King so the King can be reused hand.enqueue(12) field[card] = self.card_names[card] print(" " + str(field)) input("") elif not isinstance( field[card], str ): # If it is not a King, this checks if the slot can be filled with the card hand.enqueue(field[card]) field[card] = self.card_names[card] print(" " + str(field)) input("") else: # If nothing else can be done, the card in the hand is put in the burn pile and the cycle ends print("Nothing could be done. . .") self.burn_pile.push(card) break def check_field(self, field): """ Checks a field to see if it is been completed. :param field: field to be checked :return: A boolean """ for i in field: if not isinstance(i, str): return True return False def reset(self): """ Clears all of the hands, piles, and fields. :return: None """ del self.player_1_field[:] del self.player_2_field[:] self.draw_pile.clear() self.burn_pile.clear() self.player_1_hand.clear() self.player_2_hand.clear() def refresh(self): """ Moves all cards from the burn pile to the draw pile :return: None """ for i in range(self.burn_pile.size()): self.draw_pile.push(self.burn_pile.pop()) self.draw_pile.shuffle() def end_of_round(self): """ Prints out the progress of each player and calls reset() to end the round. :return: None """ print("Player 1 has " + str(self.player_1_round) + " cards to fill and Player 2 has " + str(self.player_2_round) + " cards to fill.") self.reset() def play(self): """ Creates the drawing pile, the fields, and goes through the placing phase until a player completes their field. Whichever players completed their field move on to the next round with 1 less slot to fill. :return: A Boolean """ self.create_draw_pile() self.create_playing_field(self.player_1_round, self.player_1_hand, self.player_1_field) self.create_playing_field(self.player_2_round, self.player_2_hand, self.player_2_field) while True: input("Player 1's turn. Press enter to start.") self.placing_phase(self.player_1_hand, self.player_1_field, self.player_1_round) input("Player 2's turn. Press enter to start.") self.placing_phase(self.player_2_hand, self.player_2_field, self.player_2_round) if not self.check_field( self.player_1_field) and not self.check_field( self.player_2_field ): # Checks if both players finished self.player_1_round -= 1 self.player_2_round -= 1 break elif not self.check_field( self.player_1_field ): # If both players didn't finish, checks if Player 1 finished self.player_1_round -= 1 break elif not self.check_field( self.player_2_field): # Checks if Player 2 self.player_2_round -= 1 break if self.player_1_round == 10 - self.rounds: # Checks if player 1 has won print("Player 1 has won!") return False elif self.player_2_round == 10 - self.rounds: # Checks if player 2 has won print("Player 2 has won!") return False else: # If neither player has won yet, this ends the round self.end_of_round() return True
def setUp(self): self.__deque = get_deque() self.__stack = Stack() self.__queue = Queue()
def __init__(self): self.enqueue_stack = Stack() self.dequeue_stack = Stack()
def rev_String(String): stack = Stack() for char in String: stack.push(char) while not stack.is_empty(): print(stack.pop() + " ")
def __init__(self): super().__init__() self.minstack = Stack()
def calPoints(self, ops): """ :type ops: List[str] :rtype: int """ a = Stack() total = 0 for operation in ops: if (operation[0] == '-' and operation[1:].isdigit()) or operation.isdigit(): a.push(int(operation)) if operation == "C": a.pop() if operation == "D": a.push(a.top() * 2) if operation == "+": a.push(a.items[-1]+a.items[-2]) for i in a.items: total += i return total
class QueueViaStack: def __init__(self): self.enqueue_stack = Stack() self.dequeue_stack = Stack() def enqueue(self, data): self.enqueue_stack.push(data) def dequeue(self): if not self.dequeue_stack.is_empty(): return self.dequeue_stack.pop() else: while not self.enqueue_stack.is_empty(): self.dequeue_stack.push(self.enqueue_stack.pop()) return self.dequeue_stack.pop() def is_empty(self): return self.dequeue_stack.is_empty() and self.enqueue_stack.is_emtpy() def peek(self): top_element = self.dequeue() self.dequeue_stack.push(top_element) return top_element
from Stack import Stack s = Stack() print s.isEmpty() s.push(4) s.push('dog') print(s.peek()) s.push(True) print(s.size()) print(s.isEmpty()) s.push(8.4) print(s.pop()) print(s.pop()) print(s.size())
def __init__(self, stack_size): super().__init__(stack_size) self.min_stack = Stack(stack_size)
from Graph import Graph from Stack import Stack stack = Stack() def routeExists(graph, a, b): if a == b: return True if graph.graphDictionary[a] = []: return False a_edges_nodes = graph.graphDictionary[a] for node in a_edges_nodes: if node == b: return True stack.push(node) while not stack.isEmpty(): node = stack.pop() return routeExists(graph, node, b)
def __init__(self, *args, **kwargs): super(StackWithMin, self).__init__(*args, **kwargs) self.min_stack = Stack()
from Recursividad import suma_lista_rec,countdown,eliminar_pila from Stack import Stack print("Prueba suma lista recursiva") datos = [4,2,3,5] res = suma_lista_rec(datos) print(f"La suma de la lista es {res}") print("\nPrueba Cuentaregresiva") countdown(20) print("\nPrueba ADT Stack") s = Stack() s.push(100) s.push(50) s.push(30) s.push(120) s.push(230) s.push(10) print("\nCaso Base") s.to_string() eliminar_pila(s) print("\nCaso despues de la funcion") s.to_string()
from Stack import Stack stack = Stack(int) #Initialise a stack object with the data type. #Gotta love them true loops. while True: try: intInput = int(input("Please enter a non-negative integer to convert to binary: ")) #Retrieve the terminal input. Convert to int. except Exception: break; if intInput < 0: break #Push these remainders and pop em out like a baby afterwards. A binary baby. while intInput != 0: stack.push(intInput % 2) intInput //= 2 while stack.top is not None: print(stack.pop(), end="") print("")
def infixToPostfix(tokenList): opStack = Stack() prec = {"^": 4, "*": 3, "/": 3, "+": 2, "-": 2, "(": 1} postfixList = [] # tokenList = list(infix.split(" ")) charTokens = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" numTokens = "1234567890" print ("token list: ", tokenList) for token in tokenList: if token in charTokens or token in numTokens or token.isdigit(): postfixList.append(token) elif token == "(": opStack.push(token) elif token == ")": topToken = opStack.pop() while topToken != "(": postfixList.append(topToken) topToken = opStack.pop() else: while (not opStack.is_empty()) and \ (prec[opStack.peek()] >= prec[token]): postfixList.append(opStack.pop()) opStack.push(token) while not opStack.is_empty(): postfixList.append(opStack.pop()) return ' '.join(postfixList)
title = row[1].strip() name = row[2].strip() last_name = row[3].strip() st = Student(str(id), str(title), str(name), str(last_name)) students.append( st) #put the st which is student object to the students list line_cnt = line_cnt + 1 print( "===================================Stack data structure===================================" ) print( '-----------------------------------create stack------------------------------' ) stStudent = Stack(45) print( '-----------------------------------Normal Flow------------------------------' ) for i in students: print("push the ", i.__str__(), "Which is student object to the stack") stStudent.push(i) while not stStudent.is_empty(): print("This is the top value of the stack: ", stStudent.peek().__str__()) print("Then take it out of the top stack by pop() it") stStudent.pop() print( '-----------------------------------Using pop all()------------------------------'