def dectobin(n):
    s=Stack()
    while (n>0):
        m=n%2
        s.push(m)
        n=int(n/2)
    return s
def revrse(expr):
	revsd=[]
	stck=Stack()
	for each in expr:
		stck.push(each)
	while stck.isEmpty() is not True:
		revsd.append(stck.pop())
	print ''.join(revsd)
示例#3
0
 def convertStack(self,stack,newBase,oldBase):
     revStack = Stack()
     while stack.length() != 0:
         revStack.push(stack.pop())
     while revStack.length() != 0:
         stack.push(Operation.__convertFromDecimal(
             Operation.__convertToDecimal(revStack.pop(),oldBase),newBase))
     del revStack
示例#4
0
    def __init__(self,numMarbles):
        self.resv = Queue()
        self.oneMin = Stack()
        self.fiveMin = Stack()
        self.hour = Stack()

        assert numMarbles >= 27
        
        for i in range(numMarbles):
            self.resv.enqueue(i)
def buildParseTree(exp_string):
	exp_list = exp_string.split()
	parent_stack = Stack()
	root = BinaryTree(None)
	current_node = root
	
	for token in exp_list:
		if token == "(":
			current_node.insertLeft(None)
			parent_stack.push(current_node)
			current_node = current_node.getLeftChild()
		
		elif token in "+-*/":
			current_node.setRootVal(token)
			parent_stack.push(current_node)
			current_node.insertRight(None)
			current_node = current_node.getRightChild()
			
		elif token == ")":
			if parent_stack.size() > 0:
				parent_node = parent_stack.pop()
				current_node = parent_node
		
		else:
			current_node.setRootVal(float(token))
			if parent_stack.size() > 0:
				parent_node = parent_stack.pop()
				current_node = parent_node
	
	return root
示例#6
0
文件: Tree_Parse.py 项目: Zoxas/Test
def buildParseTree(fpexp):
    fplist = fpexp.split()#將str以sep分割成子字串,回傳儲存子字串的串列
    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
def postEval(symbolString):
    """Given a postfix expression, evaluate it"""
    if symbolString == None:
        return None
    
    tokens = symbolString.split()
    stack = Stack()
    
    for token in tokens:
        # Is the token an integer?
        if token.isdigit():
            stack.push(int(token))
        # otherwise, it must be an operator
        elif stack.__len__() <= 1:
            print("Ill-formed expression")
            return None
        else:
            arg1 = stack.pop()
            arg2 = stack.pop()
            # Evaluate operator expressions (handles exceptions)
            val = applyOp(token, arg1, arg2)
            stack.push(val)

    if not stack.__len__() == 1:
        print("Ill-formed expression")
        return None
        
    return stack.pop()
class Queue_from_Stacks(object): 
	def __init__(self): 
		self.in_stack = Stack()
		self.out_stack = Stack()
		self.length = 0


	def is_empty(self): 
		return self.length <= 0 


	def enqueue(self, element):
		self.in_stack.push(element)
		self.length += 1 


	def dequeue(self):
		if(self.out_stack.is_empty()):
			while (not(self.in_stack.is_empty())):
				self.out_stack.push(self.in_stack.pop())
		if (not(self.out_stack.is_empty())):
			self.length -= 1
			return self.out_stack.pop()


	def __repr__(self):
		return "IN: " + str(self.in_stack) + "\nOUT: " + str(self.out_stack)
示例#9
0
def dec_to_base(dec, base):
	digits = "0123456789ABCDEF"
	s = Stack()
	while dec > 0:
		s.push(dec % base)
		dec = dec / base
	yeni = ""
	while not s.isEmpty():
		yeni = yeni + digits[s.pop()]
		
	return yeni
def to_binary_num(decimal):
	s = Stack()
	while decimal > 0:
		rem = decimal % 2
		s.push(rem)
		decimal /= 2
	ans_string = ""
	while not s.is_empty():
		ans_string += str(s.pop())
	
	return ans_string
示例#11
0
文件: decTo.py 项目: wemrekurt/Python
	def decTo(self):
		digits = "0123456789ABCDEF"
		remstack = Stack()

		while self.val > 0:
			rem = self.val % self.base
			remstack.push(rem)
			self.val = self.val / self.base

		newOne = ""
		while not remstack.isEmpty():
			newOne = newOne + digits[remstack.pop()]

		return newOne
示例#12
0
class MaxStack:
     def __init__(self):
         self.base = Stack()
         self.max = Stack()
     def push(self, item):
        if item >= self.max.peek():
            self.max.push(item)
        self.base.push(item)
     def pop(self):
         val = self.base.pop()
         if (val == self.max.peek()):
             self.max.pop()
         return val
     def getmax(self):
         return self.max.peek()
def bracketChecker(user_input):
    s = Stack()
    for c in user_input:
        if c == ("(" or "[" or "{"):
            s.push(c)
        elif c == (")" or "]" or "}"):
            if s.isEmpty():
                return False
            else:
                top = s.pop()
                if not matches(top, c):
                    return False
        else:
            pass
    return True
def balanced(expr):
	stck=Stack()
	for each in expr:
		if typeOfPara(each) is "lpar1" or typeOfPara(each) is "lpar2" or typeOfPara(each) is "lpar3":
			typ=typeOfPara(each)
			stck.push(typ)
		elif typeOfPara(each) is "rpar1" or typeOfPara(each) is "rpar2" or typeOfPara(each) is "rpar3":
			typ=typeOfPara(each)
			spop=stck.pop()
			if match(spop)==typ:
				continue
			else:
				break


	if stck.isEmpty() is not True:
		print "Unbalanced Paranthesis"
	else:
		print "Balanced Paranthesis"
def run_loop(params):
    external = params
    print 'external: ', external
    cort_neurons = [MLEF.MorrisLecarElectricField(0.2, p=0.2) for e in range(num_cort_neurons)]
    #motor_units = ST.generate_linear_spectrum_motor_units(10, 20e-04, 10e-03, 1.0, 11.0, 5.0, 10.0, 7.0, 14.0)
    motor_units = ST.generate_linear_spectrum_motor_units(10, 20e-04, 200e-03, 1.0, 11.0, 5.0, 50.0, 7.0, 70.0)
    stack = ST.Stack(run_time, cort_neurons, motor_units, cortical_soma_input=lambda t: soma_current[t], cortical_ext_input=lambda t: external)
    stack.run()
    stack.muscle.get_total_force()
    return [e.total_force for e in stack.motor_units]
 def __init__(self, Id, Location, MoviePlaying, StartTime):
     """ Creates a new instance of a showtime. """
     # Pre:
     # Id must be a valid and unique identifier, the location must be an existing at the theater, the movie must be known to the theater and the start time must correspond to one of the theater's time slots.
     self.number_of_free_seats_value = 0
     self.tickets = Stack()
     self.id = Id
     self.location = Location
     self.movie_playing = MoviePlaying
     self.start_time = StartTime
     self.number_of_free_seats = Location.number_of_seats
示例#17
0
 def __fromDecimal(self, base):
     number = str(self.getDeciValue())
     negative = True if "-" in number < 0 else False
     if negative:
         number = number[1:]
     remainders = Stack()
     separated_num = self.__separateFloat(str(float(number)))
     integer = separated_num[0]
     fraction = separated_num[1]
     number = int(integer)
     while number > 0:
         remainder = number % base
         remainders.push(int(remainder))
         number = number // base
     integer = "" if not remainders.is_empty() else "0"
     while not remainders.is_empty():
         try:
             integer += Number.__DIGITS[remainders.pop()]
         except IndexError as BaseError:
             raise Exception( "Base outside range of representable digits.") from BaseError
     fraction = "0." + fraction
     fraction = self.__convertDecimalFraction(fraction, base)
     output = integer + fraction
     if negative:
         output = "-" + output
     self.__setValue(output)
示例#18
0
def parChecker(symbolString):
	s=Stack()
	balanced = True # default
	index =0 
	while index < len(symbolString) and balanced:
		symbol=symbolString[index]
		# if (,{,[ push onto stack
		if symbol in "({[":
			s.push(symbol)
		else:
			# if stack is empty, imbalance 
			if s.isEmpty():
				balanced = False
			else:
				top=s.pop()
				if not matches(top,symbol):
					balanced = False

		index = index+1

	# balanced and no ( present 
	if balanced and s.isEmpty():
		return True
	# otherwise unbalanced ( present
	else:
		return False
 def redeem_ticket(self, Theater, Customer):
     """ Have one person redeem their ticket and enter the showtime.
         Note that a user who reserved more than one ticket must enter the showtime multiple times, once per ticket. """
     # Pre:
     # The customer must be a user who has an unredeemed ticket for this showtime.
     # The theater must be the theater containing this showtime.
     # Post:
     # If the customer does not have an unredeemed ticket for this showtime, this method does nothing.
     # If, on the other hand, the user does, their ticket is redeemed, and their absence will no longer delay the showtime.
     # If the last ticket was redeemed, the showtime begins, and is be removed from the theater's showtime list.
     if self.has_ticket(Customer):
         tempStorage = Stack()
         while not self.tickets.is_empty:
             item = self.tickets.pop()
             if item.customer == Customer:
                 break
             else:
                 tempStorage.push(item)
         while not tempStorage.is_empty:
             self.tickets.push(tempStorage.pop())
         if self.tickets.is_empty:
             Theater.showtimes.remove(self.id)
示例#20
0
 def testPop(self):
     stack = Stack()
     stack.push(0)
     stack.push(5)
     stack.push(2)
     item = stack.pop()
     self.assertEquals(item, 2)
     self.assertEquals(stack.data, [0, 5])
def DFS_iterative(Graph, node, nodes_list):
    global time
    stack = Stack()
    stack.push(node)
    while not stack.isEmpty():
        nodes_list[node].explore()
        nodes_list[node].set_leader(source_node)
        node = stack.peek()
        if len(Graph[node]) != 0:
            linked_node = Graph[node].pop()
            if nodes_list[linked_node].get_not_explored():
                stack.push(linked_node)
        else:
            time += 1
            nodes_list[stack.pop()].set_time(time)
示例#22
0
def SortStack(mystack):
	HelpStack = Stack()
	while not mystack.isEmpty():
		MaxValue = mystack.pop()
		while not HelpStack.isEmpty() and HelpStack.peek() > MaxValue:
			mystack.push(HelpStack.pop())
		HelpStack.push(MaxValue)

	return HelpStack
示例#23
0
    def TestPop(self):
        '''post: removes and returns the top element of 
        the stack'''

        stack = Stack()
        stack.push(5)
        stack.pop(5)

        self.assertEqual(stack.items[-1], 0)
示例#24
0
def print_list_reversely(p):
    s = Stack()
    li = []
    while p:
        s.push(p.elem)
        p = p.next
    while not s.is_empty():
        li.append(s.pop())
    print(li)
示例#25
0
def bin(n):
    res = Stack()
    while n != 0:
        res.push(n % 2)
        n = n // 2
    ans = ""
    while  not res.isEmpty():
        ans += str(res.pop())
    return ans
示例#26
0
def parChecker(string):
    s = Stack()
    balanced = True
    idx = 0
    while idx < len(string) and balanced:
        symbol = string[idx]
        if symbol in '([{':
            s.push(symbol)
        else:
            if s.isEmpty():
                return False
            elif not matches(s.peek(), symbol):
                return False
            s.pop()
        idx += 1

    if s.isEmpty() and balanced:
        return True
    else:
        return False
示例#27
0
def convert_infix_to_postfix(infix):
    if infix is None:
        return None

    prec_map = get_precedence_map()
    #print prec_map
    opstack = Stack.Stack()

    result_postfix = []

    for item in infix:
        print "--------------------------item: "+str(item)
        # if operand just add it to result
        if item in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or item in "0123456789":
            print "appending: "+str(item)
            result_postfix.append(item)
            opstack.print_stack()

        # if "(" just push it to stack
        elif item == "(":
            opstack.push(item)
            opstack.print_stack()

        # add to result upto open brace
        elif item == ")":
            top_elem = opstack.pop()
            while top_elem.get_data() != "(" and opstack.size > 0:
                print "appending: "+str(top_elem.get_data())
                result_postfix.append(top_elem.get_data())
                top_elem = opstack.pop()

            opstack.print_stack()
            #result_postfix.append(top_elem) # no need to append paranthesis in result.

        else:
            # should be an operator
            while opstack.size > 0 and prec_map[opstack.peek()] >= prec_map[item]:
                temp = opstack.pop()
                print "appending: "+str(temp.get_data())
                result_postfix.append(temp.get_data())


            opstack.push(item) # after popping existing operator , push the current one. (or) without popping just push. based on the precedence check.
            opstack.print_stack()
        #print result_postfix

    while opstack.size != 0:
        result_postfix.append(opstack.pop().get_data())
    return result_postfix
示例#28
0
def main():
	# initialize a stack
	mystack = Stack()
	mystack.push(3)
	mystack.push(1)
	mystack.push(5)
	mystack.push(2)
	mystack.push(4)

	sorted_stack = SortStack(mystack)

	while not sorted_stack.isEmpty():
		print sorted_stack.pop()
示例#29
0
class QueueWith2Stacks:
    def __init__(self):
        self.stack1 = Stack()
        self.stack2 = Stack()
        self.size = 0

    def add(self, item):
        self.stack1.push(item)
        self.size += 1

    def remove(self):
        for i in range(self.size):
            value = self.stack1.pop()
            self.stack2.push(value)
        firstElem = self.stack2.pop()
        self.size -= 1
        for i in range(self.size):
            value = self.stack2.pop()
            self.stack1.push(value)
        return firstElem
class Automata:
	def __init__(self):
		self.estados = Stack()


	#Este metodo se encarga de leer el fichero que incluye los estados en texto plano
	def leerArchivo(self):
		archivo = open("jugadas/5.dat", "r") 
		archivo.readline()
		#elimino el salto de linea al final
		linea = archivo.readline().rstrip('\n')
		#elimino el punto al final del texto y retorno dicho texto 
		return linea.rstrip('.')
	#Este metodo es el que crea la pila y agrega los objetos, hace un match entre los caracteres y los numeros 
	def crearPilaAutomata(self):
		guiones = self.leerArchivo()
		#guardo en la variable estados cada uno de los guiones separados por coma
		estadossinMatch = []
		estadossinMatch = guiones.split(",")
		for estado in estadossinMatch:
			
			match = re.match(r"([a-z]+)([0-9]+)",estado, re.I)
			if match:
				
				items = match.groups()
				escenario = items[0]
    			numeros = items[1]
    			cad_numero = str(numeros)
    			
    			base = cad_numero[0]
    			try:
    				jugador = int(cad_numero[1])
    			except: 
    				jugador = 0
    			
    			self.estados.push(Estado(escenario,base,jugador))
示例#31
0
    def test_delete(self):
        """! Testing of delete method """
        Stack1 = Stack.Stack()
        Stack1.push(1)
        Stack1.push(2)
        Stack1.push(3)
        Stack1.pop()
        self.assertEqual(2, Stack1.size())
        self.assertEqual(1, Stack1.getBody()[0])
        self.assertEqual(2, Stack1.getBody()[1])

        Stack2 = Stack.Stack()
        Stack2.push("1")
        Stack2.push("2")
        Stack2.push("3")
        Stack2.push("4")
        Stack2.push("5")
        Stack2.pop()
        Stack2.pop()
        Stack2.pop()
        self.assertEqual(2, Stack2.size())
        self.assertEqual("1", Stack2.getBody()[0])
        self.assertEqual("2", Stack2.getBody()[1])

        Stack3 = Stack.Stack()
        Stack3.push(1.86)
        Stack3.push(2.15)
        Stack3.push(2.34)
        Stack3.push(5.76)
        Stack3.push(9.81)
        Stack3.pop()
        self.assertEqual(4, Stack3.size())
        self.assertEqual(1.86, Stack3.getBody()[0])
        self.assertEqual(2.15, Stack3.getBody()[1])
        self.assertEqual(2.34, Stack3.getBody()[2])
        self.assertEqual(5.76, Stack3.getBody()[3])
示例#32
0
def inorder_iter(tree):
    current = tree
    s = st.Stack()
    is_done = False
    while not is_done:
        if current:
            s.push(current)
            current = current.leftChild
        else:
            if not s.is_empty():
                current = s.pop()
                print(current.key)
                current = current.rightChild
            else:
                is_done = True
    def __repr__(self):
        m = self.m
        if m == 1 or m == 0:
            raise Exception("Si le facteur de compression est de 0 ou de 1, il est impossible de créer un arbre fini.")
        stack = Stack()
        current = self.__urn
        stack.push(current)
	    

        while current.getSize() != 1:           #push chaque niveau de l'arbre sur le stack
	    
            current = current.getCompressed(m)
            stack.push(current)
            
	
        f = Queue()
        root = stack.pop().getBallot(0)         #initialisation à la racine de l'arbre (taille du premier niveau = 1)
        tree = Forest(str(root))

        f.insert(tree)
        
        while not stack.isEmpty():              #tant qu'il y a des niveaux à rajouter
                     
            level = stack.pop()                     #niveau à lier au niveau précédent
            i = 0
            toModify = f.size()                     #nombre de noeuds du niveau précédent
            while i < toModify:
                
                n = f.remove()
                node = level.getBallot(i*m)
                n.modifyChild(str(node))    #on ajoute un premier fils
                f.insert(n.getChild())                                  #on le mémorise pour modifier son fils par après
                                    
                j=1
                n = n.getChild()
                while (j < m and (i*m)+j < level.getSize()):            #on ajoute m-1 frère(s) à ce fils
                    node = level.getBallot(i*m+j)
                    n.modifyBrother(str(node))  #on ajoute un frère
                    f.insert(n.getBrother())                                #on le mémorise pour modifier son fils par après
                    n = n.getBrother()                                      #n devient le frère de n afin de lui ajouter un frère à l'itération suivante
                    j+=1

                i += 1
                
        tree.niveau(m)
        return ""
def bracket_balanced_check(s):
    stack = Stack.Stack()
    open_list = ['[', '{', '(']
    close_list = [']', '}', ')']
    for i in s:
        if i in open_list:
            stack.push(i)
        elif i in close_list:
            pos = close_list.index(i)
            if (len(stack) > 0) and open_list[pos] == stack.peek():
                stack.pop()
            else:
                return 'Unbalance'
    if len(stack) == 0:
        return 'Balanced'
示例#35
0
def test_stack_pushpushpop():
    stack = Stack.Stack()
    stack.PUSH(5)
    assert stack.S == [5] + [None] * 19
    assert stack.top == 1
    assert stack.STACK_EMPTY == False
    stack.PUSH(7)
    assert stack.S == [5, 7] + [None] * 18
    assert stack.top == 2
    assert stack.STACK_EMPTY == False
    popped = stack.POP()
    assert stack.S == [5, 7] + [None] * 18
    assert stack.top == 1
    assert popped == 7
    assert stack.STACK_EMPTY == False
示例#36
0
def is_matched(expr):
    """Return True if delimiters are properly matched. False otherwise"""
    lefty = "({["
    righty = ")}]"

    s = Stack.ArrayStack()
    for c in expr:
        if c in lefty:
            s.push(c)
        elif c in righty:
            if s.is_empty():
                return False
            if righty.index(c) != lefty.index(s.pop()):
                return False
    return s.is_empty()
示例#37
0
    def test_pop(self) -> None:
        """Test the pop function of the stack datastructures
        """
        stack = Stack()

        stack.push(2)
        stack.push(3)

        popped_item = stack.pop()
        assert (popped_item == 3) and (stack.to_list() == [2])
示例#38
0
def path_profiling(adjlist_dict):
    for key in adjlist_dict:
        route_stack = Stack.Stack()
        visited_list = []
        paths = []

        route_stack.push(key)
        visited_list.append(key)

        while not route_stack.is_empty():

            current = route_stack.top()

            #Get the unvisited neighbours for observation
            neighbours = []
            for neighbour in adjlist_dict[current][1]:
                if neighbour not in visited_list:
                    neighbours.append(neighbour)

            if len(neighbours) == 0:
                print(
                    route_stack.my_array)  #paths.append(route_stack.my_array)
                route_stack.pop()
    #
            else:
                route_stack.push(neighbours[0])
                visited_list.append(neighbours[0])


#
# #Deployment of mac addresses from a path
# for mac in mac_addresses:
#     num_neigh = 5
#     current_ap = 'ap1'
#     while num_neigh > 0:
#         adjlist_dict[current_ap][0].append(mac)
#         num_neigh = len(adjlist_dict[current_ap][1])
#         if num_neigh > 0:
#             choice = random.randrange(0, num_neigh, 1)
#             current_ap = adjlist_dict[current_ap][1][choice]
#
# keys = adjlist_dict.keys()
# for key in keys:
#     print(key, adjlist_dict[key][0])

# d = timedelta()
# for i in range(1000):
#     print(d.microseconds)
示例#39
0
def DepthFirstSearch(graph, startingNodeData):
    searchStack: Stack = Stack()
    seen: set = set([])  #visited elements

    searchStack.push(startingNodeData)

    while searchStack.isEmpty() == False:
        currentNodeData = searchStack.pop()

        if currentNodeData not in seen:
            seen.add(currentNodeData)
            print(currentNodeData)

        for neighbor in graph[currentNodeData]:
            if neighbor not in seen:
                searchStack.push(neighbor)
示例#40
0
 def move_onto(linked, a, b, n):
     move_over(linked, a, b, n)
     stack = Stack(n)
     for item in linked:
         while item.size() != 0:
             stack.push(item.pop())
             if stack.peek() == a:
                 while True:
                     x = item.pop()
                     if x == b:
                         stack.push(x)
                         break
                     linked.get(x).push(x)
         sum_stacks(item, stack)
示例#41
0
def createGraph(convexHull, pointData):
    g = igraph.Graph()
    coords = []  # Creates an initial list for the coordinates to be appended into
    edgeList =[]  # Creates an initial list for the vertex indexes to be appended into so the vertices join up
    i=1  # Create an initial index
    while convexHull.isEmpty() is not True:  # Code keeps looping until the convex hull has no more points to plot
        g.add_vertex(str(i))  # Vertex index is just the i counter -> Can't be a stop name because JSON doesn't have
                              # this information
        coords.append(convexHull.peek())  # Add the coordinates to the coordinates list
        convexHull.pop()
        if str(i) != "1":  # At i=1 there is not two edges to append to the edge list
            if int(convexHull.size()) != 0:  # The last point needs to append itself and the previous point as well
                                             # as the initial point
                edgeList.append((str(i), str(i-1)))
            else:  # Last Point
                edgeList.append((str(i), str(i-1)))
                edgeList.append((str(i), "1"))
        else:
            pass
        i += 1

    points = Stack()  # Create a stack for the point data to be added into
    for point in pointData:
        points.push(point)
    while points.isEmpty() is not True:
        g.add_vertex(str(i))  # Adds all the points (The ones in the convex hull are added again, but this does not
                              # affect the graph produced)
        latitude = points.peek()[0]  # Create lat and long variables in order to append them to the coordinate list
        longitude = points.peek()[1]
        coords.append((float(latitude), float(longitude))) # Float errors if they aren't converted to variables first
        points.pop()  # Remove the point

    g.add_edges(edgeList)  # Uses the edge list to create the edges

    visual_style = {}
    visual_style["layout"] = coords  # layout takes a 2d matrix of coordinates and uses them
                                     # to position the vertexes. bbox of 2000,2000 appears to be a
                                     # suitable size
    visual_style['bbox'] = (2000,2000)
    igraph.plot(g, **visual_style)
示例#42
0
def isPalindrome_Stacks(inp):

    i = 0
    stack = Stack.Stack()
    while inp[i] != "X":
        stack.push(inp[i])
        i = i + 1

    i = i + 1
    #stack.print_stack()

    while i < len(inp):
        if stack.size == 0 or stack.pop().get_data() != inp[i]:
            return -1
        i = i + 1
    return 1
def postfix_eval(postfix_expr):
	token_list = postfix_expr.split()
	operand_stack = Stack()
	
	for token in token_list:
		if token in "0123456789":
			operand_stack.push(int(token))
		else:
			operand1 = operand_stack.pop()
			operand2 = operand_stack.pop()
			result = do_math(operand1, operand2, token)
			operand_stack.push(result)
	
	return operand_stack.pop()
示例#44
0
 def __init__( self, master, title=__TITLE, base=__BASE) :
     self.__base = base
     #INITIALIZE THE STACK
     self.__stack = Stack()
     #Initialise the Operation class
     self.__operation = Operation(self.__stack)
     # Initialise main calculator window.
     Tk.__init__( self, master )
     # Set title.
     self.title( title )
     #Set not resizable
     self.resizable(0,0)
     # Save @master@. Not used...
     self.__master = master
     # Finish rest of initialisation.
     self.__initialise( base=base)
示例#45
0
def dec_to_base(dec, base):
    digits = "0123456789ABCDEF"
    s = Stack()
    while dec > 0:
        s.push(dec % base)
        dec = dec / base
    yeni = ""
    while not s.isEmpty():
        yeni = yeni + digits[s.pop()]

    return yeni
示例#46
0
def base_converter(dec_number, base):
   digits = "0123456789ABCDEF"
   rem_stack = Stack()
   while dec_number > 0:
      rem = dec_number % base
      rem_stack.push(rem)
      dec_number = dec_number // base
   new_string = ""
   while not rem_stack.is_empty():
      new_string = new_string + digits[rem_stack.pop()]
   return new_string
示例#47
0
def divideBybase(decnumber,base):
	digits="0123456789ABCDEF"
	remstack=Stack()
	while decnumber>0:
		rem =decnumber%base
		remstack.push(rem)
		decnumber=decnumber//base
	binstring=""
	while not remstack.isEmpty():
		binstring=binstring+digits[remstack.pop()]
	return binstring
示例#48
0
def validate(string: str):
    stack = Stack()
    
    for s in string:
        if s == '(':
            stack.push('(')
        elif s == ')':
            if stack.size == 0:
                return False
            stack.pop()
    return stack.size == 0
示例#49
0
def palindromer(s):
    new_string_stack = Stack()
    new_string =""
    
    for l in s:
        new_string_stack.push(l)
    
    while (new_string_stack.is_empty() == False):
        new_string += str(new_string_stack.pop())
    
    return print(new_string)
示例#50
0
def CheckMatchinParenthesis2(input):
    import sys
    sys.path.append("./mylib")
    import Stack
    demoStack = Stack.Stack()
    for entry in input:
        if (entry == '('):
            demoStack.push(entry)
        elif (entry == ')'):
            if (demoStack.pop() == -1):
                return ("unbalanced")
                exit
    #Check is stack is empty - more left parenthesis
    if (demoStack.mysize() == 0):
        return ("balanced")
    else:
        return ("unbalanced")
示例#51
0
    def testFunctional(self):
        s = Stack.Stack()

        self.assertTrue(s.isEmpty())

        s.push(4)
        s.push("dog")
        self.assertEqual("dog", s.peek())

        s.push(True)
        self.assertEqual(s.size(), 3)
        self.assertFalse(s.isEmpty())

        s.push(8.4)
        self.assertEqual(8.4, s.pop())
        self.assertEqual(True, s.pop())
        self.assertEqual(2, s.size())
示例#52
0
def evaluate_postfix(postfix):

    opstack = Stack.Stack()
    operators = list("+-*/")
    for item in postfix:

        if item in "0123456789":
            opstack.push(item)
        elif item in operators:
            operand1 = opstack.pop().get_data()
            operand2 = opstack.pop().get_data()
            print "operand1: " + str(operand1)
            print "operand2: " + str(operand2)
            opstack.push(doMath(
                item, operand2,
                operand1))  # note: operand2 is the earlier element in stack.
    print opstack.print_stack()
示例#53
0
def checkForBalance(stringToCheck):
    paraStack = Stack.Stack()
    for item in stringToCheck:
        if item in "({[":
            paraStack.push(item)
        else:
            if paraStack.isEmpty():
                return False
            else:
                top = paraStack.pop()
                if not matches(top, item):
                    return False

    if paraStack.isEmpty():
        return True
    else:
        return False
示例#54
0
def test_stack_pushpoppop():
    with pytest.raises(Stack.Underflow):
        stack = Stack.Stack()
        stack.PUSH(5)
        assert stack.S == [5] + [None] * 19
        assert stack.top == 1
        assert stack.STACK_EMPTY == False
        popped = stack.POP()
        assert stack.S == [5] + [None] * 19
        assert stack.top == 0
        assert popped == 5
        assert stack.STACK_EMPTY == True
        popped = stack.POP()
        assert stack.S == [5] + [None] * 19
        assert stack.top == 0
        assert popped == None
        assert stack.STACK_EMPTY == True
示例#55
0
def postfixEval(postfixExpr):
    """Evaluate the given postfix expression"""
    operandStack = Stack.Stack()
    tokenList = postfixExpr.split()

    #Scan tokenList for numbers or operators
    for token in tokenList:
        # If the token has a positive integer < 10 in it's first position, push the entire token
        if token[0] in "0123456789":
            operandStack.push(token)
        else:
            # When operator is encountered, evaluate it with the previous two operands
            operand2 = operandStack.pop()
            operand1 = operandStack.pop()
            result = doMath(token, int(operand1), int(operand2))
            operandStack.push(result)
    return operandStack.pop()
    def evalPostfix(self, result):  #계산
        s = Stack.Stack()
        try:
            for token in result:
                if token in "+-*/":
                    val2 = s.pop()
                    val1 = s.pop()

                    if token == '+': s.push(val1 + val2)
                    elif token == '-': s.push(val1 - val2)
                    elif token == '*': s.push(val1 * val2)
                    elif token == '/': s.push(val1 / val2)
                else:
                    s.push(int(token))
            return s.pop()
        except Exception:
            return None
def displayTreeWithStack(root):
    currentElement = root
    stack = Stack(currentElement, currentElement.value)
    while currentElement is not None:
        #printez elementul curent
        print(str(stack.top.key.key))
        stack = stackPop(stack)
        if currentElement.left is not None:
            stack = stackPush(stack, currentElement.left,
                              currentElement.left.value)
        if currentElement.right is not None:
            stack = stackPush(stack, currentElement.right,
                              currentElement.right.value)
        if stack.top is not None:
            currentElement = stack.top.key
        else:
            currentElement = None
    def toRegularTree(self,numberOfChildren = 2):   #1) je ne vois pas en quoi le second paramètre est nécessaire,
                                                    #   le résultat de la méthode n'est d'ailleurs pas logique si
                                                    #   numberOfChildren est différent de 2
                                                    #   je ne lui ai donné aucun rôle dans cette méthode afin d'éviter de potentielles erreurs
                                                    #2) je ne crée pas l'arbre binaire à partir de l'arbre courant
                                                    #   car si jamais (et ce n'est pas le cas dans les tests fournis)
                                                    #   on désire créer un arbre m-aire avec m > 2 en tant qu'arbre courant,
                                                    #   on sera obligé de partir du niveau le plus bas.. cad l'urne de départ..
	
        stack = Stack()
        current = self.__urn
        stack.push(current)
	    
        while current.getSize() != 1:           #push chaque niveau de l'arbre sur le stack
	    
            current = current.getCompressed(2)
            stack.push(current)
            
	
        f = Queue()
        root = stack.pop().getBallot(0)     #initialisation à la racine de l'arbre (taille du premier niveau = 1)
        tree = BinaryTree(str(root)+str(root.getIdentifier()))
        f.insert(tree)
        
        while not stack.isEmpty():          #tant qu'il y a des niveaux à rajouter
                     
            level = stack.pop()                 #niveau à lier au niveau précédent
            i = 0
            toModify = f.size()                 #nombre de noeuds du niveau précédent
            while i < toModify:                 #on ajoute un fils gauche et un fils droit à chacun de ces noeuds(un gauche minimum)       
                n = f.remove()
                node = level.getBallot(i*2)              #indice du fils gauche = indice du père * 2
                n.insertLeft(str(node) + str(node.getIdentifier()))     #ajout d'un fils gauche
                f.insert(n.getLeftChild())                              #on ajoute le fils à la liste des noeuds qui doivent être modifiés
                if i*2+1 < level.getSize():                
                    node = level.getBallot(i*2+1)        #indice du fils droit = indice du père * 2 + 1
                    n.insertRight(str(node) + str(node.getIdentifier()))#ajout d'un fils droit
                    f.insert(n.getRightChild())                         #on ajoute le fils à la liste des noeuds qui doivent être modifiés
                i += 1

        return tree
示例#59
0
    def __init__(self,size):
        ## initializes all the stacks and variables used to store info, and initializes stack object
        self.Stack = []
        self.Explore1Stack = []
        self.Explore2Stack = []
        self.SolutionStack = []
        self.linelist = []
        self.myStack = Stack.myStack()
        self.size = size

        ## self.map stores the information for all the cells, each cell has four [0,0,0,0]'s
        ## the first grouping of 0's stores info about the solution, the second grouping stores info about the solution
        ## the third grouping stores info about the borders of the maze, and the fourth grouping stores info about the walls
        ## the four 0's in each one correspond the the West,South,East and North directions
        self.map = [[[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]] for i in range(self.size + 2)] for i in range(self.size + 2)]
        self.win = GraphWin("My Maze",self.size*40+1,self.size*40+1)
        
        ## randomly chooses location for the entrance, exit and key
        self.entrance,self.exit,self.key = self.generatePoints()
示例#60
0
def postEval0():
    """Given a postfix expression, evaluate it"""
    
    symbolString = input("Input a postfix expression: ")
    tokens = symbolString.split()
    stack = Stack()
    
    for token in tokens:
        # Is the token an integer?
        if token.isdigit():
            stack.push(int(token))
        # otherwise, it must be an operator
        else:
            arg1 = stack.pop()
            arg2 = stack.pop()
            # You’ll have to write the applyOp function
            val = applyOp(token, arg1, arg2)
            stack.push(val)
    return stack.pop()