Exemple #1
0
def depth_first_search(root):
    nodes = Stack()
    nodes.append(root)

    while not nodes.empty():
        current_node = nodes.pop()
        for child in current_node.children:
            nodes.append(child)
Exemple #2
0
 def isValid(self, s):
     st = Stack()
     paren_map = {")": "(", "]": "[", ">": "<", "}": "{"}
     for c in s:
         if c not in paren_map:
             st.append(c)
         elif not st.list or paren_map[c] != st.pop():
             return False
     return not st.list
Exemple #3
0
def dfs_iterative_2(root, result):
    '''depth first search iterative implementation
        children are traversed in a different order to previous algorithms (but its more efficient)''' 
    todo = Stack()
    todo.append(root)
    while len(todo):
        node = todo.pop()
        result.append(node.visit())
        for node in node.children:
            todo.append(node)
Exemple #4
0
def dfs_iterative(root, result):
    '''depth first search iterative implementation
        in same order as for recursion'''    
    todo = Stack()
    todo.append(root)
    while len(todo):
        node = todo.pop()
        result.append(node.visit())
        for node in reversed(node.children): #reversal makes it match dfs_recursive
            todo.append(node)
Exemple #5
0
def evaluate_posfix_expression(expression):
    elements = [x for x in expression.split(' ') if x]
    operands = ['+', '-', '*', '/']
    stack = Stack()

    for e in elements:
        if e.isdigit():
            stack.append(e)
        elif e in operands:
            n1 = stack.pop()
            n2 = stack.pop()
            res = str(eval(n1 + e + n2))
            stack.append(res)

    return int(stack.pop())
 def print_in_line(self):
     if not self.size:
         print('')
         return
     from stack import Stack
     from queue import Queue
     q = Queue()
     q.append(self.head)
     A = Stack()
     A.append(self.head.key)
     while q.size:
         cur = q.popleft()
         for nei in [cur.left, cur.right]:
             if nei is not None:
                 q.append(nei)
                 A.append(nei.key)
     return A.arr
Exemple #7
0
    def test_append(self):
        A = Stack()
        A.append(3)
        A.append(101)
        self.assertEqual(A.arr, [3, 101])

        A = Stack()
        with self.assertRaises(AssertionError):
            A.append('qwerty')

        A.append((3, {3: 0}))
        self.assertEqual(A.arr, [(3, {3: 0})])
def isCorrespond(string: str):
    left = ['[', '{', '(']
    # right = ['}', '}', ')']
    pair = ["[]", "{}", "()"]
    stack = Stack()
    for symbol in string:
        if symbol in left:
            stack.append(symbol)
        else:
            leftSymbol = stack.pop()
            if leftSymbol is None:
                return False
            elif leftSymbol + symbol in pair:
                continue
            else:
                return False

    if stack.is_empty():
        return True
    else:
        return False
def inorder_iterative_visit1(root, result):
    '''
    in-order, iterative implementation.
    
    requires a visited flag to be added to each node.
    not very elegant, but obvious solution to cycling problem.
    In python I don't think this solution is better than the recursive one,
    because we still have a stack -> so mem usage is the same.
    In C++ or java, the stack should be declared on the heap...
    otherwise I don't see what is the gain. 
    '''
    todo = Stack()
    todo.append( root )
    while len(todo):
        node = todo.peek()
        if node:
            if not node.visited:
                node.visited = True
                todo.append( node.left )
            else:
                result.append( node.visit() ) # changed to node.visit to make more general
                todo.pop()
                todo.append( node.right )
        else:
            print 'none'
            todo.pop()
Exemple #10
0
def inorder_iterative_visit2(root, result):
    '''cleaner and more understandable than visit1, but there is still 
    a visited flag'''
    todo = Stack()
    todo.append( root )
    while len(todo):
        node = todo.pop()
        if node:
            if not node.visited:
                node.visited = True
                todo.append( node ) # re-adding the node for second visit
                todo.append( node.left )
            else:
                result.append( node.visit() ) # changed to node.visit to make more general
                todo.append( node.right )
Exemple #11
0
def inorder_iterative(root, result):
    '''Finally, without the visited flag... 
    took me some time to find this one...'''
    todo = Stack()
    todo.append( root )
    last = None
    while len(todo):
        node = todo.pop()
        if node:
            if not last or (last.left is node or last.right is node):
                todo.append( node )
                todo.append( node.left )
            else:
                result.append( node.visit() ) # changed to node.visit to make more general
                todo.append( node.right )
            last = node 
Exemple #12
0
def infixToPostfix(string: str) -> str:
    """ Convert infix operations to postfix operations
    """
    precedence = {}
    precedence["*"] = 3
    precedence["/"] = 3
    precedence["+"] = 2
    precedence["-"] = 2
    precedence["("] = 1

    operationStack = Stack()
    output = []

    tokenList = string.split("").strip()
    for token in tokenList:

        if token in letters:
            output.append(token)

        elif token == LEFT_PAREN:
            operationStack.append(token)

        elif token == RIGHT_PAREN:
            topToken = operationStack.pop()
            while topToken != LEFT_PAREN:
                output.append(token)
                topToken = operationStack.pop()
        else:
            top = operationStack.peek()
            while not operationStack.isEmpty(
            ) and precedence[top] >= precedence[token]:
                output.append(operationStack.pop())
            operationStack.append(token)
    while not operationStack.isEmpty():
        output.append(operationStack.pop())

    return " ".join(output)
Exemple #13
0
def test_all():
    s = Stack()
    s.append(10) #integer test
    s.append(10.1) #float test
    s.append("String Test") #string test
    string = s.pop() #pop string
    float = s.pop() #pop float
    integer = s.pop() #pop integer
    print(string, float, integer)
Exemple #14
0
def preorder_iterative(root, result):
    '''pre-order, iterative implementation'''
    todo = Stack()
    todo.append(root)
    while len(todo):
        node = todo.pop()
        if node.right:
            todo.append(node.right)
        if node.left:
            todo.append(node.left)
        result.append( node.visit() )
Exemple #15
0
def graham_hull(points):
    points = transform_points(points)

    stack = Stack()
    stack.append(points[0])
    stack.append(points[1])
    stack.append(points[2])

    for i in range(3, len(points)):
        while len(stack) > 1 and ccw(stack.one_below_top(), stack.top(), points[i]) < 0:
            stack.pop()
        stack.append(points[i])

    return stack
Exemple #16
0
def postorder_iterative_1(root, result):
    '''We effectively find the nodes from last to first
    so when we find each node we append to the start of the result not the back    
    This version uses visited'''
    todo = Stack()
    todo.append( root )
    while len(todo):
        node = todo.peek()
        if node:
            if not node.visited:
                node.visited = True
                result.insert(0,node.visit()) #add to back
                todo.append( node.right )
            else:
                todo.pop()
                todo.append( node.left )
        else:
            todo.pop()
Exemple #17
0
def postorder_iterative(root, result):
    '''version without visited
    we find the nodes from last to first
    so each node is inserted at the start of the result not the back
    an alternative might be to reverse the result at the end'''  
    todo = Stack()
    todo.append( root )
    last = None
    while len(todo):
        node = todo.peek()
        if node:
            if not last or last.right is node or last.left is node:
                result.insert(0,node.visit())
                todo.append( node.right )
            else:
                todo.pop()
                todo.append( node.left )
            last=node
        else:
            todo.pop()
Exemple #18
0
def infix_to_postfix(expression, precedence='normal'):
    # characters = list(expression.replace(' ', ''))
    precedences = {
        'equal': {
            '+': 0,
            '-': 0,
            '*': 0,
            '/': 0,
            '(': -1
        },
        'normal': {
            '+': 0,
            '-': 0,
            '*': 1,
            '/': 1,
            '(': -1
        },
        'reverse': {
            '+': 1,
            '-': 1,
            '*': 0,
            '/': 0,
            '(': -1
        }
    }
    if precedence not in precedences:
        raise ValueError(
            "Precedence argument must be one of ['normal', 'equal', 'reverse']"
        )

    operands_precedence = precedences[precedence]
    characters = list(expression)
    postfix = ""
    stack = Stack()

    for c in characters:
        if c.isdigit():
            postfix += c
        elif c == ' ':
            postfix += c
        elif c == '(':
            stack.append(c)
        elif c == ')':
            while not stack.is_empty() and stack.top() != '(':
                top = stack.pop()
                postfix += ' '
                postfix += top
            if not stack.is_empty() and stack.top() == '(':
                stack.pop()

        elif c in operands_precedence:  # Operator
            while not stack.is_empty() and \
                operands_precedence[c] <= operands_precedence[stack.top()]:
                postfix += ' '
                postfix += stack.pop()

            stack.append(c)

    while not stack.is_empty():
        postfix += ' '
        postfix += stack.pop()

    return postfix
Exemple #19
0
def test_integers():
    s = Stack()
    s.append(5)
    t = s.pop()
    print(t)
Exemple #20
0
def test_strings():
    s = Stack()
    s.append("Test String")
    t = s.pop()
    print(t)
Exemple #21
0
def test_floats():
    s = Stack()
    s.append(3.14)
    t = s.pop()
    print(t)
Exemple #22
0
class Menu:
    "Show the calculator interface, handles user input"
    STATUS_LINE_Y = 0
    STACK_X = 0
    STACK_SIZE = 5
    MSG_LINE_Y = STATUS_LINE_Y + STACK_SIZE + 2

    def __init__(self):
        "Initialize an empty stack"
        self.stack = Stack()
        self.message_line = ""

    def get_status_line(self):
        "Show angle unit at top of calculator"
        if self.stack.conv == 1.0:
            return "RAD"
        else:
            return "DEG"

    def get_input(self, prompt="> "):
        """Handles user input key by key :
            - [esc] or "q" to quit the calculator
            - [enter] to duplicate last stack element or to lauch the command being constituted
            - [backspace] to remove last stack element
            - +, -, * and / operands to execute the operation
            - any other key to constitute the command or a stack element"""
        result = ""
        prompt_y = self.STATUS_LINE_Y + 1 + self.STACK_SIZE
        while True:
            self.stdscr.addstr(prompt_y, self.STACK_X,
                               "                       ")
            self.stdscr.addstr(prompt_y, self.STACK_X, prompt + result)
            curses.flushinp()
            key = self.stdscr.getch()
            if key == 27 or (chr(key) == "q" and result == ""):
                result = "q"
                break
            elif key == 127 or key == 263:
                if result == "":
                    result = "drop"
                    break
                else:
                    result = result[:-1]
            elif key == 13 or key == 10:
                break
            elif chr(key) in ["+", "-", "*", "/", "!"]:
                if result == "":
                    result = chr(key)
                else:
                    result += " " + chr(key)
                break
            else:
                result += chr(key)
        self.message_line = ""
        return result

    def print_stack(self):
        "Print stack content on screen, plus status and message lines"
        self.stdscr.addstr(self.STATUS_LINE_Y, self.STACK_X,
                           self.get_status_line())
        for y in range(0, self.STACK_SIZE):
            line_y = self.STATUS_LINE_Y + self.STACK_SIZE - y
            try:
                self.stdscr.addstr(line_y, self.STACK_X,
                                   str(self.stack[-y - 1]))
            except:
                break
        self.stdscr.addstr(self.MSG_LINE_Y, self.STACK_X, self.message_line)

    def will_it_float(self, str):
        "Indicate wether a string can be converted to float or not"
        try:
            float(str)
            return True
        except ValueError:
            return False

    def run(self):
        "Handles user input wher the [enter] key is pressed"
        self.stdscr = curses.initscr()
        curses.noecho()
        curses.cbreak()
        self.stdscr.keypad(True)
        try:
            while True:
                self.stdscr.clear()
                self.print_stack()
                cmds = self.get_input()
                for cmd in cmds.split(" "):
                    saved_stack = copy.deepcopy(self.stack)
                    try:
                        if self.will_it_float(cmd):
                            self.stack.append(float(cmd))
                        else:
                            self.stack.execute_command(cmd)
                    except StackUnderflowException as e:
                        self.message_line = str(e)
                        self.stack = saved_stack
                    except ZeroDivisionError as e:
                        self.message_line = "division by zero"
                        self.stack = saved_stack
                    except AngleUnitChangeException as e:
                        pass  # Nothing to do, just re-show stack
                    except UnknownCommandException as e:
                        self.message_line = str(e)
                    except QuitException as e:
                        self.message_line = str(e)
                        exit(0)
                    except Exception as e:
                        self.message_line = str(e)
                        self.stack = saved_stack
        finally:
            self.stdscr.keypad(False)
            curses.nocbreak()
            curses.echo()
            curses.endwin()
Exemple #23
0
 def test_pop(self):
     A = Stack()
     self.assertEqual(A.pop(), None)
     A.append(2)
     self.assertEqual(A.pop(), 2)
Exemple #24
0
class Gaot(object):
	def __init__(self):
		self.stack = Stack([])
		self.instructions = None
		self.ipointer = 0
		self.move = 1
		self.BAA = re.compile(r"ba{2,}")
		self.BLEET = re.compile(r"ble{2,}t")

		self.commands = [self._add,        #2
					   self._subtract,     #3
					   self._continue,     #4
					   self._exit,         #5
					   self._reverse,      #6
					   self._skiptrue,     #7
					   self._skipfalse,    #8
					   self._printnum,     #9
					   self._printchar,    #10
					   self._getnum,       #11
					   self._getchar,      #12
					   self._dupe,         #13
					   self._swap,         #14
					   self._reverse_stack,#15
					   self._rotate_stack] #16
		self.ccount = 0

	def run(self, program):
		self.instructions = program.split()
		while self.ipointer < len(self.instructions):
			c = self.instructions[self.ipointer]

			if self.BAA.search(c): # is a "baa" command
				self.stack.append(len(c) - 2)

			elif self.BLEET.search(c): # is a "bleet" command
				n = len(c) - 3
				self.commands[n-2]()
			self.ipointer += self.move

	def get_code(self):
		if "--file" in sys.argv:
			code = open(sys.argv[sys.argv.index("--file") + 1]).read()

			input_index = sys.argv.index("--file")

			sys.argv.pop(sys.argv.index("--file") + 1)
			sys.argv.pop(sys.argv.index("--file"))

		elif len(sys.argv) >= 2:
			code = sys.argv[1]
			input_index = 2
		else:
			code = raw_input("Code: ")

		try:
			self.input = sys.argv[input_index:]
		except:
			self.input = []
		return code


	# --------------------------------------

	def _add(self):
		self.stack.push(self.stack.pop() + self.stack.pop())

	def _subtract(self):
		self.stack.push(self.stack.pop() - self.stack.pop())

	def _continue(self):
		self.ipointer += self.move

	def _exit(self):
		exit()

	def _reverse(self):
		self.move *= -1

	def __skip(self, state):
		self.ipointer += self.move*(self.stack.pop() == state)

	def _skiptrue(self):
		self.__skip(True)

	def _skipfalse(self):
		self.__skip(False)

	def _printnum(self):
		sys.stdout.write(unicode(self.stack.pop()))
		sys.stdout.flush()

	def _printchar(self):
		sys.stdout.write(unicode(chr(self.stack.pop())))
		sys.stdout.flush()

	def _getnum(self):
		self.stack.push(float(raw_input()))

	def _getchar(self):
		_ = ord(getch())
		self.stack.append(_*(_!=4))

	def _dupe(self):
		self.stack.push(self.stack.peek())

	def _swap(self):
		x,y = self.stack.pop(), self.stack.pop()

		self.stack.push(y)
		self.stack.push(x)

	def _reverse_stack(self):
		self.stack = Stack(self.stack.get()[::-1])

	def _rotate_stack(self):
		_ = self.stack.get()
		self.stack = Stack(x[1:]+x[0])
Exemple #25
0
from stack import Stack
from path import root
from Tree import Node
from check import checker

start = root
end = str(input("between b-f"))

s = Stack()

count = 1

s.append(root)
x = s.print()
while len(x) != 0:
    if len(x) == 0:
        print("no Solution")
    else:

        y = s.stack[-1]
        print(y.data)
        result = checker(y.data, end)
        print(result)
        if result is True:
            print(f"element found at {count}")
            exit()
        else:
            s.pop()
            if y.child1 is not None:
                s.append(y.child1)
            if y.child2 is not None:
Exemple #26
0
class Gaot(object):
    def __init__(self):
        self.stack = Stack([])
        self.instructions = None
        self.ipointer = 0
        self.move = 1
        self.BAA = re.compile(r"ba{2,}")
        self.BLEET = re.compile(r"ble{2,}t")

        self.commands = [
            self._add,  # 2
            self._subtract,  # 3
            self._continue,  # 4
            self._exit,  # 5
            self._reverse,  # 6
            self._skiptrue,  # 7
            self._skipfalse,  # 8
            self._printnum,  # 9
            self._printchar,  # 10
            self._getnum,  # 11
            self._getchar,  # 12
            self._dupe,  # 13
            self._swap,  # 14
            self._reverse_stack,  # 15
            self._rotate_stack,
        ]  # 16
        self.ccount = 0

    def run(self, program):
        self.instructions = program.split()
        while self.ipointer < len(self.instructions):
            c = self.instructions[self.ipointer]

            if self.BAA.search(c):  # is a "baa" command
                self.stack.append(len(c) - 2)

            elif self.BLEET.search(c):  # is a "bleet" command
                n = len(c) - 3
                self.commands[n - 2]()
            self.ipointer += self.move

    def get_code(self):
        if "--file" in sys.argv:
            code = open(sys.argv[sys.argv.index("--file") + 1]).read()

            input_index = sys.argv.index("--file")

            sys.argv.pop(sys.argv.index("--file") + 1)
            sys.argv.pop(sys.argv.index("--file"))

        elif len(sys.argv) >= 2:
            code = sys.argv[1]
            input_index = 2
        else:
            code = raw_input("Code: ")

        try:
            self.input = sys.argv[input_index:]
        except:
            self.input = []
        return code

        # --------------------------------------

    def _add(self):
        self.stack.push(self.stack.pop() + self.stack.pop())

    def _subtract(self):
        self.stack.push(self.stack.pop() - self.stack.pop())

    def _continue(self):
        self.ipointer += self.move

    def _exit(self):
        exit()

    def _reverse(self):
        self.move *= -1

    def __skip(self, state):
        self.ipointer += self.move * (self.stack.pop() == state)

    def _skiptrue(self):
        self.__skip(True)

    def _skipfalse(self):
        self.__skip(False)

    def _printnum(self):
        sys.stdout.write(unicode(self.stack.pop()))
        sys.stdout.flush()

    def _printchar(self):
        sys.stdout.write(unicode(chr(self.stack.pop())))
        sys.stdout.flush()

    def _getnum(self):
        self.stack.push(float(raw_input()))

    def _getchar(self):
        _ = ord(getch())
        self.stack.append(_ * (_ != 4))

    def _dupe(self):
        self.stack.push(self.stack.peek())

    def _swap(self):
        x, y = self.stack.pop(), self.stack.pop()

        self.stack.push(y)
        self.stack.push(x)

    def _reverse_stack(self):
        self.stack = Stack(self.stack.get()[::-1])

    def _rotate_stack(self):
        _ = self.stack.get()
        self.stack = Stack(x[1:] + x[0])
def LEXdfs(graph, start):
    """
    Does DFS search of graph, beginning at start.
    Implemented from Algorithm 1 in
    "Finding compact communities in large graphs"
    by Creusefond, Largillier and Peyronnet.
    http://dx.doi.org/10.1145/2808797.2808868 
    """

    #
    # Create and initialize VISITED and LEX for all nodes
    #
    attrs = { VISITED: {},
              LEX: {}}
    
    node = graph.BegNI()
    while node < graph.EndNI():
        attrs[VISITED][node.GetId()] = 0
        attrs[LEX][node.GetId()] = "0"
        node.Next()
    
    # initialize DFS variables
    stack = Stack()
    stack.append( start.GetId() )
    i = 1

    # do the search
    while len(stack) > 0:

        # print "stack:"
        # print node_list_to_str(graph, stack, attrs)
        # print
        # print
        
        # process top node
        # print
        # stack.print_all()
        # print
        node_id = stack.pop()
        node = graph.GetNI(node_id)
        attrs[VISITED][node_id] = i
        array = []
        
        # find unvisited neighbors of node
        for in_id in range(node.GetOutDeg()):
            out_id = node.GetOutNId(in_id)
            out_node = graph.GetNI(out_id)
            if attrs[VISITED][out_id] == 0:
                # will raise exception if out_node not there
                try:
                    # print "Trying to remove", node_to_str(graph, out_id, attrs)
                    stack.remove(out_id)
                    # print "Removed", node_to_str(graph, out_id, attrs)
                except ValueError as e:
                    # expected to occur
                    pass

                attrs[LEX][out_id] = str(i) + attrs[LEX][out_id]
                array.append(out_id)

            # end of unvisited neighbor
        # end of neighbors

        # print "Not sure if this is correct.  Needs to randomize order for ties"
        # print "Before"
        # print node_list_to_str(graph, array, attrs)
        array.sort(key = lambda n_id: attrs[LEX][n_id])
        randomize_equal_neighbors(graph, array, attrs)
        # print "After"
        # print node_list_to_str(graph, array, attrs)
        # print
        # print
        stack.extend(array)
        i = i + 1
        # print "stack:"
        # print node_list_to_str(graph, stack, attrs)
        # print
        # print

    # end of stack processing
    
    return attrs