コード例 #1
0
def solveMaze(row, column, maze):
    stack = ArrayStack()
    stack.push((row, column))

    while not stack.isEmpty():
        (row, column) = stack.peek()
        if maze[row][column] == 'T':
            return stack
        elif maze[row][column] != '.':
            maze[row][column] = '.'
            counter = 0  ###adjacent cells based on changing x,y values so need 4 options
            if row != 0 and not maze[row - 1][column] in ('*', '.'):
                stack.push((row-1, column))
                counter += 1
            if row + 1 != maze.getHeight() and not maze[row + 1][column] in ('*', '.'):
                stack.push((row + 1, column))
                counter += 1
            if column + 1 != maze.getWidth() and not maze[row][column + 1] in ('*', '.'):
                stack.push((row, column + 1))
                counter += 1
            if column != 0 and not maze[row][column -1] in ('*', '.'):
                stack.push((row, column - 1))
                counter += 1
        if counter == 0:
            stack.pop()
    return None
コード例 #2
0
def is_matched_html(raw):
	""" Returns True if all HTML tags are properly matched, False otherwise """
	S = ArrayStack()

	j = raw.find('<')                 # find first < character if any

	while j != -1:
		k = raw.find(">",j+1)         # find next > character if any

		if k==-1:
			return False              # invalid tag

		tag = raw[j+1:k]              # dtrip away <>

		if not tag.startswith('/'):
			S.push(tag)
		else:
			if S.is_empty():
				return False
			if tag[1:] != S.pop():
				return False

		j = raw.find("<",k+1)

	return S.is_empty()
コード例 #3
0
class StackQueue:
    def __init__(self):
        self.stack1 = ArrayStack()
        self.stack2 = ArrayStack()
        self.count = 0

    def enqueue(self, item):
        self.stack1.push(item)
        self.count += 1

    def dequeue(self):
        if self.is_empty():
            raise ValueError("Empty Queue Error")

        self.moveStack1ToStack2()
        return self.stack2.pop()

    def peek(self):
        if self.is_empty():
            raise ValueError("Empty Queue Error")

        self.moveStack1ToStack2()
        return self.stack2.peek()

    def moveStack1ToStack2(self):
        if self.stack2.is_empty():
            while not self.stack1.is_empty():
                self.stack2.push(self.stack1.pop())

    def is_empty(self):
        return self.stack1.is_empty() and self.stack2.is_empty()
コード例 #4
0
def post_fix_eval(expr):
    """
    후위 표현식으로 된 식을 계산
    :param expr:
    :return:
    """
    val_stack = ArrayStack()

    for token in expr:
        if isinstance(token, int):
            val_stack.push(token)
        elif token == '+':
            num1 = val_stack.pop()
            num2 = val_stack.pop()
            val_stack.push(num2 + num1)
        elif token == '-':
            num1 = val_stack.pop()
            num2 = val_stack.pop()
            val_stack.push(num2 - num1)
        elif token == '/':
            num1 = val_stack.pop()
            num2 = val_stack.pop()
            val_stack.push(num2 / num1)
        elif token == '*':
            num1 = val_stack.pop()
            num2 = val_stack.pop()
            val_stack.push(num2 * num1)

    return val_stack.pop()
コード例 #5
0
ファイル: model.py プロジェクト: gregpuzzles1/Sandbox
class PFEvaluator(object):
   
    def __init__(self, scanner):
        self._expressionSoFar = ""
        self._operandStack = ArrayStack()
        self._scanner = scanner

    def evaluate(self):
        while self._scanner.hasNext():
            currentToken = self._scanner.next()
            self._expressionSoFar += str(currentToken) + " "
            if currentToken.getType() == Token.INT:
                self._operandStack.push(currentToken)
            elif currentToken.isOperator(): 
                if len(self._operandStack) < 2:
                    raise Exception, \
                          "Too few operands on the stack"
                t2 = self._operandStack.pop()
                t1 = self._operandStack.pop()
                result = Token(self._computeValue(currentToken,
                                                  t1.getValue(),
                                                  t2.getValue()))
                self._operandStack.push(result)

            else:
                raise Exception, "Unknown token type"
        if len(self._operandStack) > 1:
            raise Exception, "Too many operands on the stack"
        result = self._operandStack.pop()
        return result.getValue();   

    def __str__(self):
        result = "\n"
        if self._expressionSoFar == "":
            result += "Portion of expression processed: none\n"
        else: 
            result += "Portion of expression processed: " + \
                   self._expressionSoFar + "\n"
        if self._operandStack.isEmpty():
            result += "The stack is empty"
        else:
            result += "Operands on the stack          : " + \
                      str(self._operandStack)
        return result

    def _computeValue(self, op, value1, value2):
        result = 0;
        theType = op.getType()
        if theType == Token.PLUS:
            result = value1 + value2;
        elif theType == Token.MINUS:
            result = value1 - value2;
        elif theType == Token.MUL:
            result = value1 * value2;
        elif theType == Token.DIV:
            result = value1 / value2;
        else:
            raise Exception, "Unknown operator" 
        return result
コード例 #6
0
    def test_is_empty(self):
        # empty stack
        stack = ArrayStack()
        self.assertTrue(stack.is_empty())

        # non-empty stack
        stack.push('a')
        self.assertFalse(stack.is_empty())
コード例 #7
0
class PFEvaluator(object):
    def __init__(self, scanner):
        self._expressionSoFar = ""
        self._operandStack = ArrayStack()
        self._scanner = scanner

    def evaluate(self):
        while self._scanner.hasNext():
            currentToken = self._scanner.next()
            self._expressionSoFar += str(currentToken) + " "
            if currentToken.getType() == Token.INT:
                self._operandStack.push(currentToken)
            elif currentToken.isOperator():
                if len(self._operandStack) < 2:
                    raise Exception, \
                          "Too few operands on the stack"
                t2 = self._operandStack.pop()
                t1 = self._operandStack.pop()
                result = Token(
                    self._computeValue(currentToken, t1.getValue(),
                                       t2.getValue()))
                self._operandStack.push(result)

            else:
                raise Exception, "Unknown token type"
        if len(self._operandStack) > 1:
            raise Exception, "Too many operands on the stack"
        result = self._operandStack.pop()
        return result.getValue()

    def __str__(self):
        result = "\n"
        if self._expressionSoFar == "":
            result += "Portion of expression processed: none\n"
        else:
            result += "Portion of expression processed: " + \
                   self._expressionSoFar + "\n"
        if self._operandStack.isEmpty():
            result += "The stack is empty"
        else:
            result += "Operands on the stack          : " + \
                      str(self._operandStack)
        return result

    def _computeValue(self, op, value1, value2):
        result = 0
        theType = op.getType()
        if theType == Token.PLUS:
            result = value1 + value2
        elif theType == Token.MINUS:
            result = value1 - value2
        elif theType == Token.MUL:
            result = value1 * value2
        elif theType == Token.DIV:
            result = value1 / value2
        else:
            raise Exception, "Unknown operator"
        return result
コード例 #8
0
    def test_peek(self):
        # empty stack
        stack = ArrayStack()
        with self.assertRaises(StackException):
            stack.peek()

        # add one thing then peek. it should still be there
        stack.push('a')
        self.assertEqual(stack.peek(), 'a')
        self.assertEqual(stack.peek(), 'a')
コード例 #9
0
ファイル: reverse_file.py プロジェクト: adarsh9780/Programs
def reverse():
    S = ArrayStack()
    original = open(sys.argv[1])
    for line in original:
        S.push(line)
    original.close()

    output = open(sys.argv[1], 'w')
    while not S.is_empty():
        output.write(S.pop())
    output.close()
コード例 #10
0
ファイル: reverseFile.py プロジェクト: XBOOS/playgournd
    def reverse_file(filename):
        S = ArrayStack()
        original = open(filename)
        for line in original:
            S.push(line.rstrip("\n"))
        original.close()

        output = open(filename, "w")
        while not S.is_empty():
            output.write(S.pop() + "\n")
        output.close()
コード例 #11
0
ファイル: reverseFile.py プロジェクト: XBOOS/playgournd
    def reverse_file(filename):
        S = ArrayStack()
        original = open(filename)
        for line in original:
            S.push(line.rstrip("\n"))
        original.close()

        output = open(filename, 'w')
        while not S.is_empty():
            output.write(S.pop() + "\n")
        output.close()
コード例 #12
0
def multiBaseOutput(num, b):
    stk = ArrayStack()
    s1 = ''

    while num != 0:
        stk.push(str(num % b))
        num = num // b

    while not stk.isEmpty():
        s1 += stk.pop()

    return s1
コード例 #13
0
    def test_size(self):
        # empty stack
        stack = ArrayStack()
        self.assertEqual(stack.size(), 0)

        # one item
        stack.push('a')
        self.assertEqual(stack.size(), 1)

        # +1 item
        stack.push('b')
        self.assertEqual(stack.size(), 2)
コード例 #14
0
def reverse_file(filename):
    """ Overwrite given file with its contents line-by-line reversed. """
    S = ArrayStack()
    original = open(filename)
    for line in original:
        S.push(line.rstrip('\n'))  # we will re-insert newlines when writing
    original.close()

    # now we overwrite with contents in LIFO order
    output = open(filename, 'w')
    while not S.is_empty():
        output.write(S.pop() + '\n')
    output.close()
コード例 #15
0
def is_matched(expr):
    lefty = '({['
    righty = ')}]'
    S = 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()
コード例 #16
0
def is_matched(expr):
	lefty = '({['
	righty = ')}]'
	S = 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()
コード例 #17
0
def is_matched(expr):
    """ Return True if all delimiters are properly match;False otherwise. """
    lefty = '({['
    righty = ')}]'
    S = 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()
コード例 #18
0
def infix_to_potfix(token_list):
    """
    들어온 중위 표현식을 후위 표현식으로 변경
    :param token_list:
    :return: 후위 표현식
    """
    prec = {'*': 3, '/': 3, '+': 2, '-': 2, '(': 1}

    opStack = ArrayStack()
    result = []

    for token in token_list:
        if isinstance(token, int):
            result.append(token)
        elif token == '(':
            opStack.push(token)
        elif token == ')':
            while opStack.peek() != '(':
                result.append(opStack.pop())
            opStack.pop()
        else:
            if not opStack.isEmpty():
                if prec[opStack.peek()] >= prec[token]:
                    result.append(opStack.pop())
                    opStack.push(token)
                else:
                    opStack.push(token)
            else:
                opStack.push(token)

    while not opStack.isEmpty():
        result.append(opStack.pop())

    print(result)
    return result
def reverse_file(filename):
    """ overwrite given file with its contents line by line reversed """
    S = ArrayStack()

    original = open(filename)
    for line in original:
        S.push(line.rstrip('\n'))
    original.close()

    output = open(filename, "w")

    while not S.is_empty():
        output.write(S.pop() + "\n")
    output.close()
コード例 #20
0
    def test_push(self):
        """
        We can push an item on the stack. We should not get an error
        """
        stack = ArrayStack()

        # nothing sent it
        with self.assertRaises(TypeError):
            stack.push()

        # add a bunch of items and push. no errors
        mixed_list = [1, 'a', [6, 7, 8], {"cat": "sylvester"}, None]
        for item in mixed_list:
            stack.push(item)
コード例 #21
0
def print_reverse_order():
    words_stack = ArrayStack()
    stop = False
    while not stop:
        word = input('Please input a word: ').strip()
        if word == 'stop':
            stop = True
            break
        words_stack.push(word)
    
    reverse = ''
    while not words_stack.is_empty():
        reverse += (f' {words_stack.pop()}')

    print(f'Your words in reverse order: {reverse.lstrip()}') 
コード例 #22
0
ファイル: delimiter.py プロジェクト: Pato91/msft
def balanced(expr):
    ''' checks if all the delimiters in an expression, expr, are balanced '''
    lefts = '({[' # opening delimiters
    rights = ')}]' # respective closing delimiters
    stack = Stack()

    for d in expr:
        if d in lefts:
            stack.push(d) # first left delimiter, save for later check
        elif d in rights:
            if stack.is_empty(): # closing delimiter with no matching opening delimiter
                return False
            if rights.index(d) != lefts.index(stack.pop()): #compare match
                return False
    return stack.is_empty() # check if all symbols were matched
コード例 #23
0
ファイル: maze.py プロジェクト: xaliceli/cs1520-maze
    def solve(self, showSolution=False):
        """
        Uses backtracking algorithm to solve maze.
        Returns "SUCCESS" or "FAILURE" if the maze can or cannot be solved.
        Optionally, prints the solved maze.
        """

        # Instantiate empty stack to record coordinates to evaluate.
        coords = ArrayStack()

        # Search for starting point.
        # Push onto coords when found.
        searching = True
        while searching:
            for row in range(self.getHeight()):
                for col in range(self.getWidth()):
                    if self._data[row][col] == self._start:
                        coords.push((row, col))
                        searching = False
                        print "Starting point found at (%d, %d)." % (row, col)
            if searching:
                raise Exception("No valid starting point found.")

        # Search for end point value until found, or until
        # no possible moves exist.
        searching = True
        while searching:
            active = coords.pop()
            if active:
                activeValue = self._data[active[0]][active[1]]
                if activeValue == self._path:
                    self.setCoord(active[0], active[1], ".")
                adjacent = findAdjacent(active[0], active[1], self.getHeight(),
                                        self.getWidth())
                for coord in adjacent:
                    if self._data[coord[0]][coord[1]] == self._end:
                        print("SUCCESS: Endpoint found at (%d, %d)." %
                              (coord[0], coord[1]))
                        if showSolution:
                            print "Solution: \n", str(self)
                        searching = False
                    elif self._data[coord[0]][coord[1]] == self._path:
                        coords.push(coord)
            else:
                print "FAILURE: No solution found."
                if showSolution:
                    print "Attempted solution: \n", str(self)
                searching = False
コード例 #24
0
def is_matched(expr):
    """ Return True if all the delimeter are properly matched """
    lefty = "({["
    righty = ")}]"

    S = 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()
コード例 #25
0
def DFS(G, a):
	status={}
	for node in G.nodes():
		status[node]='U'
	nodes=ArrayStack()
	nodes.push(a)
	status[a]='V'
	while nodes.isempty()==False:
		pnode=nodes.pop()
		status[pnode]='P'
		print(pnode)
		for node in G.neighbors(pnode):
			if status[node]=='U':
				nodes.push(node)
				status[node]='V'
	return
コード例 #26
0
ファイル: stackreverse.py プロジェクト: Pato91/msft
def reverse():
    ''' replace the text in a file by a reverse of itself '''

    stack = Stack()

    # read original data into stack
    with open('text.txt', 'r') as original:
        for line in original:
            stack.push(line.rstrip('\n'))
        original.close()

    # write data from stack to file
    with open('text.txt', 'w') as output:
        while not stack.is_empty():
            output.write(stack.pop() + '\n')
        output.close()
コード例 #27
0
def maze_solver(maze, starting_pt, target_pt):
    """Implement backtracking algorithms using a stack to solve a maze"""
    if_solvable = False
    maze_stack = ArrayStack()
    path = {}
    maze_stack.push(starting_pt)
    while not maze_stack.isEmpty():
        location = maze_stack.pop()
        if maze[location[0]][location[1]] == 'T':
            if_solvable = True
        elif maze[location[0]][location[1]] != '.':
            maze[location[0]][location[1]] = '.'
            nrs = check_neighbours(maze, location[0], location[1])
            for nr in nrs:
                maze_stack.push(nr)
                path[nr] = location
    return if_solvable, path
コード例 #28
0
ファイル: army.py プロジェクト: Canyanwu/BattleGame
    def __assign_army(self, name: str, sold: int, arch: int, cav: int,
                      formation: int) -> str:
        """ method sets the formation of the army to either stack or queue form, depending on
            the value of formation (0 = stack and 1 = queue)

        # @ Complexity: The inner loop runs O(n), n been the size of each army chosen and the outer
        run is constant, so the best case is O(1) and the worst case is O(n) for both formation 0
        and formation 1
        """
        sol_object = Soldier()  # calling Soldier object
        ach_object = Archer()  # calling Archer object
        cav_object = Cavalry()  # calling Cavalry object

        player_input = [sold, arch, cav]  # list containing player input
        size = len(player_input)  # length of the player input -- 3
        player_object = [sol_object, ach_object,
                         cav_object]  # player soldier, archer, cavalry
        stack_size = sum([sold, arch, cav])  # size of the players

        # reverse the stack to enable the soldiers be the FirstInFirstOut  and Cavalry LastInLastOut
        # pushing in a reverse order, solders first and cavalry last.
        if formation == 0:
            player_stack = ArrayStack(
                stack_size)  # created stack to hold the armies purchased
            for i in range(size - 1, -1, -1):  #
                army_object = player_object[i]
                quantity = player_input[i]
                for j in range(quantity):
                    player_stack.push(army_object)
            self.force = player_stack

        # Circular Queue implementation
        # appending in a queue style
        if formation == 1:
            player_queue = CircularQueue(
                stack_size)  # created Queue to hold the armies purchased
            for i in range(size):
                army_object = player_object[i]
                quantity = player_input[i]
                for j in range(quantity):
                    player_queue.append(army_object)
            self.force = player_queue

        self.name = name
コード例 #29
0
def bracketsBalance(exp, Open, Close):
    """exp represents the expression"""
    stk = ArrayStack()  # Create a new stack
    for ch in exp:  # Scan across the expression
        if ch in Open:  # Push an opening bracket
            stk.push(ch)
        elif ch in Close:  # Process a closing bracket
            if stk.isEmpty():  # Not balanced
                return False
            chFromStack = stk.pop()
            # Brackets must be of same type and match up

            OpenIndex = Open.index(chFromStack)
            CloseIndex = Close.index(ch)

            if OpenIndex != CloseIndex:
                return False

    return stk.isEmpty()  # They all matched up
コード例 #30
0
def is_matched_html(raw):
    """ Return True if all HTML tags are properly match; False otherwise. """
    S = ArrayStack()
    # find():返回子字符串 sub 在 s[start:end] 切片内被找到的最小索引。 可选参数 start 与 end 会被解读为切片表示法。 如果 sub 未被找到则返回 -1。
    j = raw.find('<')  # find first'<' character
    while j != -1:
        k = raw.find('>', j + 1)  # find next '>'
        if k == -1:
            return False
        tag = raw[j + 1:k]
        if not tag.startswith('/'):
            S.push(tag)
        else:
            if S.is_empty():
                return False
            if tag[1:] != S.pop():
                return False
        j = raw.find('<', k + 1)
    return S.is_empty()
コード例 #31
0
ファイル: matchHTMLtag.py プロジェクト: XBOOS/playgournd
def isMatchedHTML(raw):
    # find "<" then find next ">", after that,  get the tag if starting with / then it is the ending tag, pop.otherwise, it is starting tag,push into stack
    S = ArrayStack()
    i = raw.find("<")  # this will find the first "<"

    while i != -1:
        j = raw.find(">", i + 1)
        if j == -1:
            return False
        tag = raw[i + 1:j]
        if not tag.startswith("/"):
            S.push(tag)
        else:
            if S.is_empty():
                return False
            else:
                if S.pop() != tag[1:]:
                    return False
        i = raw.find("<", j + 1)
    return S.is_empty()
コード例 #32
0
ファイル: matchHTMLtag.py プロジェクト: XBOOS/playgournd
def isMatchedHTML(raw):
    # find "<" then find next ">", after that,  get the tag if starting with / then it is the ending tag, pop.otherwise, it is starting tag,push into stack
    S = ArrayStack()
    i = raw.find("<")  # this will find the first "<"

    while i != -1:
        j = raw.find(">", i + 1)
        if j == -1:
            return False
        tag = raw[i + 1 : j]
        if not tag.startswith("/"):
            S.push(tag)
        else:
            if S.is_empty():
                return False
            else:
                if S.pop() != tag[1:]:
                    return False
        i = raw.find("<", j + 1)
    return S.is_empty()
コード例 #33
0
ファイル: is_bracket.py プロジェクト: lowelllll/DataStructure
def is_brackets(expr):
    match = {
        ')':'(',
        ']':'[',
        '}':'{'
    }

    S = ArrayStack()

    for c in expr:
        if c in '({[':
            S.push(c)
        else:
            if S.isEmpty():
                return False
            else:
                bracket = S.pop()
                if bracket != match[c]:
                    return False

    return S.isEmpty() # 스택이 비어있지 않으면 괄호가 안맞음.
コード例 #34
0
ファイル: taglint.py プロジェクト: Pato91/msft
def closetags(html):
    ''' checks if all tags in a html block are closed '''
    stack = Stack()

    # is there an opening angle? find it
    i = html.find('<')

    while i != -1:
        j = html.find('>', i + 1)  # finding the next > character
        if j == -1:
            return False  # invalid tag
        tag = html[i + 1:j]  # slice of the tag from html
        if not tag.startswith('/'):
            stack.push(tag)  # its an opening tag, store in stack
        else:
            if stack.is_empty():
                return False  # closing tag found without an opening tag
            if tag[1:] != stack.pop():
                return False  # mismatched tag
        i = html.find('<', j + 1)
    return stack.is_empty()
コード例 #35
0
class TestArrayStack(unittest.TestCase):
    def setUp(self):
        self.st = ArrayStack()

    def tearDown(self):
        del self.st

    # default feature test - push, pop, peek
    def test_01(self):
        self.st.push(1)
        self.st.push(2)
        self.st.push(3)
        self.assertEqual(self.st.peek(), 3)
        self.assertEqual(self.st.pop(), 3)
        self.assertEqual(self.st.peek(), 2)
        self.assertEqual(self.st.pop(), 2)
        self.assertEqual(self.st.peek(), 1)
        self.assertEqual(self.st.pop(), 1)

    # raise error when pop with empty stack
    def test_02(self):
        with self.assertRaises(IndexError) as cm:
            self.st.pop()
        self.assertEqual("stack is empty", str(cm.exception))

    # test check empty
    def test_03(self):
        self.assertTrue(self.st.is_empty())

    # test expand
    def test_04(self):
        self.assertEqual(len(self.st._array), 10)
        for i in range(11):
            self.st.push(i)
        self.assertEqual(len(self.st._array), 20)
コード例 #36
0
ファイル: matchParentheses.py プロジェクト: XBOOS/playgournd
def isMatch(s):
    left = "{[("
    right = ")]}"
    S = ArrayStack()

    for c in s:
        if c in left:
            S.push(c)
        elif c in right:
            # what id didnt have before
            # should check empty first
            if S.is_empty():
                return False
            # if right.index(c) != left.index(S.pop())
            #      return False
            cc = S.pop()
            if not cc+c in ["{}","()","[]"]:
                return False
        else:
            raise Exception("Invalid string")
    if S.is_empty():
        return True
    else:
        return False