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()
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()
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())
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()
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()
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
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()
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)
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()
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()
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()
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()
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()
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()
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()
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()
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()
def is_matched(string): #创建一个栈 s = ArrayStack() left = '{[(' right = '}])' #遍历这个字符串 for c in string: #如果c在left中则放入s中 if c in left: s.push(c) elif c in right: if s.is_empty(): #如果c在栈中,但是栈却为空说明缺少左边的匹配 列如 ))、{)}、{[)]} return False #c在right中,拿c在right中的索引 和 栈顶元素在left中的索引做比较,并且移除栈顶元素。列如 (}、([})、[}] if right.index(c) != left.index(s.pop()): return False #如果string为(( ,缺少右侧括号匹配,则栈不为空,返回false return s.is_empty()
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
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
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()}')
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()
class PreorderIteratorStack(Generic[T]): def __init__(self, root: BinaryTreeNode[K, I]) -> None: self.stack = ArrayStack() self.stack.push(root) def __iter__(self): return self def __next__(self) -> T: if self.stack.is_empty(): raise StopIteration current = self.stack.pop() if current.right is not None: self.stack.push(current.right) if current.left is not None: self.stack.push(current.left) return current.item
#!/usr/local/bin/python3.5 from stack import ArrayStack theStack = ArrayStack() theList = [1, 2, 4, 6, 8, 9, 12, 14, 16] for item in theList: theStack.push(item) while not theStack.is_empty(): print(theStack.pop())