示例#1
0
def is_matching(expr):
    """
    Return True if delimiters in expr match correctly, False otherwise
    Parameters
    ----------
    test_str: str or unicode
        expression to evaluate parameters correctness
    Returns
    -------
        Boolean
    """
    delimiters_map = {'(': ')', '{': '}', '[': ']'}

    stack = ArrayStack()

    for c in expr:
        if c in delimiters_map:
            stack.push(c)
        elif c in delimiters_map.itervalues():
            if stack.is_empty() or delimiters_map[stack.top()] != c:
                return False
            else:
                stack.pop()

    return stack.is_empty()
class QueueUsingStacks:
    def __init__(self):
        self._stack1 = ArrayStack()
        self._stack2 = ArrayStack()

    def __len__(self):
        # to do
        return len(self._stack1) + len(self._stack2)

    def is_empty(self):
        # to do
        return (len(self._stack1) + len(self._stack2)) == 0

    def enqueue(self, e):
        # to do
        self._stack1.push(e)

    def dequeue(self):
        # to do
        if self.is_empty() == True:
            raise Empty
        elif self._stack2.is_empty() == False:
            return self._stack2.pop()
        else:
            while self._stack1.is_empty() == False:
                temp = self._stack1.pop()
                self._stack2.push(temp)
            return self._stack2.pop()
示例#3
0
def is_valid_html(raw_html):
    """
    Return True if the each opening html tag in the raw_html string has and associated closing html tag.
    Parameters
    ----------
    raw_html: str or unicode
        The raw html string we need to check for validity
    Returns
    -------
        Boolean
    """
    def is_opening_tag(tag):
        return not tag.startswith('/')

    stack = ArrayStack()
    opening_idx = raw_html.find('<')
    while opening_idx != -1:
        closing_idx = raw_html.find('>', opening_idx + 1)
        if closing_idx == -1:
            return False
        tag = raw_html[opening_idx + 1:closing_idx]

        if is_opening_tag(tag):
            stack.push(tag)
        else:
            if stack.is_empty() or stack.top() != tag[1:]:
                return False
            else:
                stack.pop()
        opening_idx = raw_html.find('<', closing_idx + 1)

    return stack.is_empty()
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')  # reopening file overwrites original
    while not S.is_empty():
        output.write(S.pop() + '\n')  # re-insert newline characters
    output.close()
示例#5
0
def match_paranthesis(expression):
    """Checks if the parantheses from the expression match up correctly"""
    stack=ArrayStack()
    for s in expression:
        if s == '(':
            stack.push(s)
        if s == ')':
            if stack.is_empty():
                return False
            else:
                stack.pop()
    return stack.is_empty()
示例#6
0
class QueueUsingStacks:
    def __init__(self):
        self._stack1 = ArrayStack()
        self._stack2 = ArrayStack()

    def __len__(self):
        return len(self._stack1)

    def is_empty(self):
        return len(self._stack1) == 0

    def enqueue(self, e):
        self._stack1.push(e)

    def dequeue(self):
        while len(self._stack1) != 1:
            self._stack2.push(self._stack1.pop())
        self._stack1.pop()
        while len(self._stack2) != 0:
            self._stack1.push(self._stack2.pop())
 def test_push_two_then_pop(self):
     stack = ArrayStack()
     stack.push(1)
     stack.push(2)
     res = stack.pop()
     self.assertEqual(res, 2)
     self.assertEqual(stack.list(), [1])
class ArrayStack:
    """LIFO Stack implementation using a Python list as underlying storage."""
    def __init__(self):
        """Create an empty stack."""
        self._data = []  # nonpublic list instance

    def __len__(self):
        """Return the number of elements in the stack."""
        return len(self._data)

    def is_empty(self):
        """Return True if the stack is empty."""
        return len(self._data) == 0

    def push(self, e):
        """Add element e to the top of the stack."""
        self._data.append(e)  # new item stored at end of list

    def top(self):
        """
        Return (but do not remove) the element at the top of the stack.

        Raise Empty exception if the stack is empty.
        """
        if self.is_empty():
            raise Exception('Stack is empty')
        return self._data[-1]  # the last item in the list

    def pop(self):
        """Remove and return the element from the top of the stack (i.e., LIFO).

        Raise Empty exception if the stack is empty.
        """
        if self.is_empty():
            raise Exception('Stack is empty')
        return self._data.pop()  # remove last item from list

    if __name__ == '__main__':

        from array_stack import ArrayStack
        s = ArrayStack()

        # question 3 of take home exam
        s.push(3)  # bottom
        s.push(2)  # middle
        s.push(1)  # top

        x = s.pop()
        if x < s.top():
            x = s.top()

        print x
示例#9
0
def reverse_file(file_path):
    stack = ArrayStack()
    with open(file_path, 'r') as f:
        for line in f:
            stack.push(line.rstrip('\n'))

    with open(file_path, 'w') as f:
        while not stack.is_empty():
            f.write(''.join([stack.pop(), '\n']))
示例#10
0
def evaluate_expression(tokens):
    stack = ArrayStack()
    for token in tokens:
        try:
            token = int(token)
            stack.push(token)
        except ValueError:
            try:
                arg_2 = stack.pop()
                arg_1 = stack.pop()
                stack.push({
                    '+': add,
                    '-': sub,
                    '*': mul,
                    '/': truediv
                }[token](arg_1, arg_2))
            except EmptyStackError:
                return
    if stack.is_empty():
        return
    value = stack.pop()
    if not stack.is_empty():
        return
    return value
示例#11
0
def is_matched(expr):
    """Return True if all delimiters are matched; False otherwise"""
    openers = '([{'
    closers = ')]}'
    S = ArrayStack()
    for c in expr:
        if c in openers:
            S.push(c)
        elif c in closers:
            if S.is_empty():  #nothing to match
                return False
            elif closers.index(c) != openers.index(S.pop()):  #mismatched
                return False
    return S.is_empty()  #Are all opening brackets matched?
def is_matched(expr):
    """Return True if all delimiters are properly match; False otherwise."""
    lefty = '({['                               # opening delimiters
    righty = ')}]'                              # respective closing delims
    S = ArrayStack()
    for c in expr:
        if c in lefty:
            S.push(c)                               # push left delimiter on stack
        elif c in righty:
            if S.is_empty():
                return False                          # nothing to match with
            if righty.index(c) != lefty.index(S.pop()):
                return False                          # mismatched
            return S.is_empty()                         # were all symbols matched?
def is_matched_delimiters(expr):
    sym_stack = ArrayStack()
    lefty = "[{("
    righty = "]})"
    for c in expr:
        if c in lefty:
            sym_stack.push(c)
        elif c in righty:
            if sym_stack.is_empty():
                return False
            e = sym_stack.pop()
            if lefty.index(e) != righty.index(c):
                return False
    return sym_stack.is_empty()
def evaluate(expression):
    operands = ArrayStack()

    for token in expression:
        if token in OPERATORS:
            b = operands.pop()  # second operand
            a = operands.pop()  # first operand

            if token == '/' and b == 0:
                return 'Cannot divide by zero, try again.'
            elif token == '^' and b < 1 and a < 0:
                return 'Cannot root negative number, try again.'
            else:
                operands.push(calculate(b, a, token))

        else:
            operands.push(float(token))

    return operands.pop()
def reverse_file(filename):
    """Overwrite given file with its contents reversed line-by-line"""
    S = ArrayStack()
    original = open(filename)
    for line in original:
        S.push(line.rstrip('\n'))             #we will re-insert newlines when writing
    original.close()

    #Now overwrite contents with LIFO order
    output = open(filename, 'w')
    while not S.is_empty():
        output.write(S.pop() + '\n')
    output.close()
def is_matched(expr):
    """Return True if all delimiters are properly match; False otherwise."""
    lefty = '({['  # opening delimiters
    righty = ')}]'  # respective closing delims
    S = ArrayStack()
    for c in expr:
        if c in lefty:
            S.push(c)  # push left delimiter on stack
        elif c in righty:
            if S.is_empty():
                return False  # nothing to match with
            if righty.index(c) != lefty.index(S.pop()):
                return False  # mismatched
    return S.is_empty()  # were all symbols matched?
示例#17
0
def is_matched_html(raw):
    """Return True if all HTML tags are propery matched; False otherwise"""
    S = ArrayStack()
    j = raw.find('<')  #find first opening tag
    while j != -1:  #while there are still opening tags left
        k = raw.find('>', j + 1)  #find next closing tag
        if k == -1:
            return False
        tag = raw[j + 1:k]  #strip off brackets... TODO: only select tag name
        if not tag.startswith('/'):  #this is an opening tag
            S.push(tag)
        else:  #closing tag
            if S.is_empty():  #nothing to match with
                return False
            if tag[1:] != S.pop():
                return False  #mismatched
        j = raw.find('<', k + 1)  #find next delimiter
    return S.is_empty()  #were all opening tags matched?
def delimiter_matched_v2(expr: str) -> bool:
    """
    >>> delimiter_matched_v2('[(2+x)*(3+y)]')
    True

    >>> delimiter_matched_v2('{[{(xbcd))]}')
    False
    """
    S = ArrayStack()
    d = {")": "(", "]": "[", "}": "{"}

    for c in expr:
        if c in d.values():
            S.push(c)
        elif c in d:
            if S.is_empty() or d[c] != S.pop():
                return False
    return S.is_empty()
示例#19
0
def is_matched_html(raw):
    """Return True if all HTML tags are properly match; False otherwise."""
    S = ArrayStack()
    j = raw.find('<')  # find first '<' character (if any)
    while j != -1:
        k = raw.find('>', j + 1)  # find next '>' character
        if k == -1:
            return False  # invalid tag
        tag = raw[j + 1:k]  # strip away < >
        if not tag.startswith('/'):  # this is opening tag
            S.push(tag)
        else:  # this is closing tag
            if S.is_empty():
                return False  # nothing to match with
            if tag[1:] != S.pop():  # tag[1:] strip away '/'
                return False  # mismatched delimiter
        j = raw.find('<', k + 1)  # find next '<' character (if any)
    return S.is_empty()  # were all opening tags matched?
示例#20
0
def is_matched_html(string):
    tag_stack = ArrayStack()
    open_idx = string.find("<")
    while open_idx != -1:
        close_idx = string.find(">", open_idx + 1)
        if close_idx == -1:
            return False
        tag = string[open_idx + 1:close_idx]
        if tag.startswith("/"):  # It is close tag
            if tag_stack.is_empty():
                return False
            if tag_stack.pop() != tag[1:]:
                return False
        else:
            tag_stack.push(tag)

        open_idx = string.find("<", close_idx + 1)

    return tag_stack.is_empty()
def delimiter_matched_v1(expr):
    """Return True if all delimiters are properly match; False otherwise.

    >>> delimiter_matched_v1('[(2+x)*(3+y)]')
    True

    >>> delimiter_matched_v1('{[{(xbcd))]}')
    False
    """
    left, right = '({[', ')}]'
    S = ArrayStack()

    for c in expr:
        if c in left:
            S.push(c)
        elif c in right:
            if S.is_empty() or right.index(c) != left.index(S.pop()):
                return False
    return S.is_empty()
示例#22
0
def is_matched_html(raw):
    stack = ArrayStack()
    j = raw.find('<')

    while j != -1:
        k = raw.find('>', j + 1)  # find next '>'
        if k == -1:
            return False

        tag = raw[j + 1:k]  # < > 之间的内容
        if not tag.startswith('/'):  # it's a opening tag
            stack.push(tag)
        else:
            if stack.is_empty():
                return False
            if tag[1:] != stack.pop():
                return False  # mismatched delimiter

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

    return stack.is_empty()
def is_matched_html(raw):
    """Return True if all HTML tags are properly match; False otherwise."""
    S = ArrayStack()
    j = raw.find('<')  # find first '<' character (if any)
    while j != -1:
        k = raw.find('>', j + 1)  # find next '>' character
        if k == -1:
            return False  # invalid tag
        tag = raw[j + 1:k]  # strip away < >
        if not tag.startswith('/'):  # this is opening tag
            S.push(tag)
        else:  # this is closing tag
            if S.is_empty():
                return False  # nothing to match with
            if tag[1:] != S.pop():
                return False  # mismatched delimiter
        j = raw.find('<', k + 1)  # find next '<' character (if any)
    return S.is_empty()  # were all opening tags matched?
示例#24
0
def text2notes(text):
    '''
    Takes text and maps it to notes.
    '''
    notes = []  # The notes
    num_stack = ArrayStack()  # Our stack of numbers

    for ch in text:  # Iterate over every character in the string
        note = __get_mapping(ch)  # Get the mapping
        if ch.isdigit():
            # If digit, add to num_stack
            num_stack.push(int(ch))
        elif ch.lower() == repeat_char and not num_stack.is_empty():
            # If the repeat character and numbers on the stack,
            # pop the most recent number and call the repeat function
            __append_repeat(notes, num_stack.pop())
        elif note != None:
            # If the note has a mapping, add it to notes
            notes.append(note)

    return notes
示例#25
0
def cal_simple_expression(exp):
    """只有+-*/四种运算, 运算数为整数, 运算符前后有空格."""
    end = '$'  # 表达式结束标志, 最低优先级
    priority = {end: 0, '+': 1, '-': 1, '*': 2, '/': 2}
    operator_func = {'+': add, '-': sub, '*': mul, '/': truediv}

    operand = ArrayStack()
    operator = ArrayStack()

    exp = exp.split()
    exp.append(end)  # 添加表达式结束标志以计算最终结果

    i = 0
    while i < len(exp):
        e = exp[i]
        if e not in priority.keys():
            operand.push(int(e))
            i += 1
        else:
            # 高优先级运算符直接push
            if operator.is_empty() or priority[e] > priority[operator.top()]:
                operator.push(e)
                i += 1

            # 低优先级运算符在下一次循环时处理
            else:
                func = operator_func[operator.pop()]
                num1 = operand.pop()
                num2 = operand.pop()
                operand.push(func(num2, num1))

    return operand.pop()
 def test_is_empty_when_pushed_and_deleted(self):
     stack = ArrayStack()
     stack.push(1)
     stack.pop()
     self.assertTrue(stack.isEmpty())
 def test_is_empty_when_pushed(self):
     stack = ArrayStack()
     stack.push(1)
     self.assertFalse(stack.isEmpty())
 def test_is_empty_when_empty(self):
     stack = ArrayStack()
     self.assertTrue(stack.isEmpty())
 def test_push_one(self):
     stack = ArrayStack()
     stack.push(1)
     self.assertEqual(stack.list(), [1])
     self.assertEqual(stack.peek(), 1)
示例#30
0
def parse_expression(tokens):
    stack = ArrayStack()
    for token in tokens:
        stack.push(token)
        if token in [')', '}', ']']:
            try:
                right = stack.pop()
                arg_2 = stack.pop()
                if type(arg_2) == str:
                    arg_2 = BinaryTree(int(arg_2))
                operate = stack.pop()
                arg_1 = stack.pop()
                if type(arg_1) == str:
                    arg_1 = BinaryTree(int(arg_1))
                left = stack.pop()
            except EmptyStackError:
                return
            except ValueError:
                return
            if (left, right) not in [('(', ')'), ('{', '}'), ('[', ']')]:
                return
            parse_tree = BinaryTree(operate)
            parse_tree.left_node = arg_1
            parse_tree.right_node = arg_2
            stack.push(parse_tree)
    if stack.is_empty():
        return
    parse_tree = stack.pop()
    if not stack.is_empty():
        return
    if type(parse_tree) == str:
        parse_tree = BinaryTree(int(parse_tree))
    return parse_tree
 def test_push_to_full(self):
     stack = ArrayStack(5)
     for i in range(5):
         stack.push(i)
     with self.assertRaises(ValueError):
         stack.push(5)
示例#32
0
 def setUp(self):
     self.array_stack = ArrayStack()
#!/usr/bin/env python3
#
#       Author:    TianJun
#       E-mail:    [email protected]
#       Website:   www.tianjun.ml
#
#       File Name: R6_3.py
#       Description:
#           transfer stack
#
#       Last Modified:
#           2014-06-27 10:15:20


from array_stack import ArrayStack, Empty


def transfer(s, t):
    while(len(s)>0):
        t.push(s.pop())

if __name__ == '__main__':
    s = ArrayStack()
    t = ArrayStack()
    for i in range(10):
        s.push(i)
    transfer(s, t)
    for i in range(10):
        print(t.pop())
示例#34
0
from array_stack import ArrayStack
a = '((()(){([()])}))'
cd = '((({{}})))'
b= '()(()){([()])}'
c=')(()){([()])}'
d='(}'

S=ArrayStack()
list_a = []
for i in a:
    if i=='(' or i=='{' or i=='[':
        S.push(i)
        print("1",S.data)
    elif i==')' and S.top()=='(':
        S.pop()
        print("2",S.data)
    elif i=='}' and S.top()=='{':
        S.pop()
        print("3",S.data)
    elif i==']' and S.top()=='[':
        S.pop()
        print("4",S.data)



print(S.is_empty())
def reverse(L):
    s = ArrayStack()
    for i in range(len(L)):
        s.push(L[i])
    for i in range(len(L)):
        L[i] = s.pop()
 def test_pop_empty(self):
     stack = ArrayStack()
     with self.assertRaises(ValueError):
         res = stack.pop()
示例#37
0
class TestArrayStackFunctions(unittest.TestCase):

    def setUp(self):
        self.array_stack = ArrayStack()

    def testArrayStackInitialize(self):
        self.assertIsNotNone(self.array_stack)
        self.assertEqual(self.array_stack.count, 0)

    def testArrayStackGet(self):
        self.array_stack.add(0, 'a')
        value = self.array_stack.get(0)
        self.assertEqual('a', value)

    def testArrayStackSet(self):
        self.array_stack.add(0, 'a')
        value = self.array_stack.set(0, 1)
        self.assertEqual('a', value)
        self.assertIn(1, self.array_stack.array)
        self.assertEqual(1, self.array_stack.count)

    def testArrayStackAdd(self):
        self.array_stack.add(0, 'a')
        self.assertEqual(self.array_stack.count, 1)
        self.assertIn('a', self.array_stack.array)

    def testArrayStackRemove(self):
        self.array_stack.add(0, 'a')
        value = self.array_stack.remove(0)
        self.assertEqual('a', value)
        self.assertEqual(0, self.array_stack.count)
 def __init__(self):
     self._stack1 = ArrayStack()
     self._stack2 = ArrayStack()
#       E-mail:    [email protected]
#       Website:   www.tianjun.ml
#
#       File Name: R6_4.py
#       Description:
#           recursively remove elements in stack
#
#       Last Modified:
#           2014-06-27 10:25:25


from array_stack import ArrayStack, Empty


def recursive_remove(s):
    if len(s) > 0:
        s.pop()
        recursive_remove(s)
    else:
        pass

if __name__ == '__main__':
    s = ArrayStack()
    for i in range(100):
        s.push(i)
    recursive_remove(s)
    try:
        s.pop()
    except Empty as e:
        print(e)