def test_pop(self): stack = PyListStack() stack.push("A") stack.push("B") assert stack._data == ['A', 'B'] assert stack.__len__() == 2 assert stack.pop() == "B"
def reverse_file(fl_name): """Overwrite given file with its contents line-by-line reversed.""" stack = PyListStack() original_file = open(fl_name) for line in original_file: stack.push(line.rstrip('\n')) # re-insert newlines when writing original_file.close() # Overwrite with contents in LIFO order reversed_file = open(fl_name, 'w') # reopening file overwrites original while not stack.is_empty(): reversed_file.write(stack.pop() + '\n') # re-insert newline characters reversed_file.close()
def int_to_bin(int_num): """Converts integer into binary number using stack.""" stack = PyListStack() while int_num > 0: remainder = int_num % 2 stack.push(remainder) int_num = int_num // 2 bin_num = "" while not stack.is_empty(): bin_num += str(stack.pop()) return bin_num
def is_matched(expr): """Return True if all delimiters are properly match; False otherwise.""" lefty = '({[' # opening delimiters righty = ')}]' # respective closing delimiters stack = PyListStack() for c in expr: if c in lefty: stack.push(c) # push left delimiter on stack elif c in righty: if stack.is_empty(): return False # nothing to match with if righty.index(c) != lefty.index(stack.pop()): return False # mismatched return stack.is_empty() # were all symbols matched?
def is_html_matched(raw): """Return True if all HTML tags are properly matched; False otherwise.""" stack = PyListStack() c1 = raw.find('<') # find first '<' character (if any) while c1 != -1: c2 = raw.find('>', c1 + 1) # find next '>' character if c2 == -1: return False # invalid tag tag = raw[c1 + 1:c2] # strip away <> if not tag.startswith('/'): # this is opening tag stack.push(tag) else: if stack.is_empty(): return False # nothing to match with if tag[1:] != stack.pop(): return False # mismatched delimiter c1 = raw.find('<', c2 + 1) # find next '<' character (if any) return stack.is_empty() # were all opening tags matched?
def is_paren_matched(input_string): """Return True if all delimiters are properly match; False otherwise.""" opening_del = '({[' # opening delimiters closing_del = ')}]' # respective closing delimiters stack = PyListStack() for c in input_string: if c in opening_del: stack.push(c) # push opening delimiter on stack elif c in closing_del: if stack.is_empty(): return False # nothing to match with else: top = stack.pop() if closing_del.index(c) != opening_del.index(top): return False # mismatched return stack.is_empty() # were all symbols matched?