class Queue: def __init__(self): self.enq = ArrayStack() self.deq = ArrayStack() def __len__(self): return len(self.deq) def is_empty(self): return len(self.deq) == 0 def first(self): if self.deq.is_empty(): raise Exception("Queue is Empty") else: return self.deq.top() def enqueue(self, val): if self.deq.is_empty(): self.deq.push(val) else: for q in range(len(self.deq)): self.enq.push(self.deq.pop()) self.enq.push(val) for q in range(len(self.enq)): self.deq.push(self.enq.pop()) def dequeue(self): if self.deq.is_empty(): raise Exception("Queue is Empty") else: return self.deq.pop()
class MyQueue: def __init__(self): self._stack = ArrayStack() self._inverted = False self._size = 0 def peek(self): # stack = self._stack if self._stack.is_empty(): raise Empty('Stack is empty') if not self._inverted: self.invert_stack() return self._stack.peek() def push(self, value): if self._inverted: self.invert_stack() self._stack.push(value) def pop(self): if self._stack.is_empty(): raise Empty('Empty stack') if not self._inverted: self.invert_stack() return self._stack.pop() def invert_stack(self): temp = ArrayStack() self._inverted = not self._inverted while self._stack.peek() is not None: temp.push(self._stack.pop()) self._stack = temp
class StackQueue(): """Implement ADT queue using two stacks""" def __init__(self): self._s = ArrayStack() self._t = ArrayStack() def __len__(self): return len(self._s) + len(self._t) def is_empty(self): return self._s.is_empty() and self._t.is_empty() def enqueue(self, value): self._s.push(value) def dequeue(self): if not self._t.is_empty(): return self._t.pop() else: if self._s.is_empty(): raise ValueError("Empty Queue") else: while not self._s.is_empty(): self._t.push(self._s.pop()) return self._t.pop()
class MaxStack: def __init__(self): self.data = ArrayStack() def __len__(self): return len(self.data) def is_empty(self): return len(self.data) == 0 def top(self): if (self.data.is_empty()): raise Exception("Stack is empty") return self.data.top()[0] def push(self, val): if self.data.is_empty(): self.data.push((val, val)) elif self.data.top()[1] > val: self.data.push((val, self.data.top()[1])) else: self.data.push((val, val)) def pop(self): if self.data.is_empty(): raise Exception("Stack is empty") return self.data.pop()[0] def max(self): if self.data.is_empty(): raise Exception("Stack is empty") return self.data.top()[1]
def is_matched_html(raw): S = ArrayStack() j = raw.find('<') while j != -1: k = raw.find('>', j + 1) if k == -1: return False tag = raw[j + 1:k] many = tag.split(" ") if len(many) > 1: if not check_atributes(many[1:]): return False tag = many[0] if not tag.startswith('/'): # its opening tag S.push(tag) else: # its ending tag if S.is_empty(): return False if tag[1:] != S.pop(): return False j = raw.find('<', k + 1) return S.is_empty()
def check(expression): stack = ArrayStack() for delimeter in expression: if delimeter in left: stack.push(delimeter) # add delemeter to stack elif delimeter in right: if stack.is_empty(): return False if left.index(stack.pop()) != right.index(delimeter): return False return stack.is_empty() # return true if all delimeters are matched
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_match(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 "Valid" if S.is_empty() else "Invalid"
def is_matched(expr): """ Returns true if the arithmatic express is true, false otherwise """ left = '({[' right = ')}]' s = ArrayStack() for c in expr: if c in left: s.push(c) elif c in right: if s.is_empty(): return False if right.index(c) != left.index(s.pop()): return False return s.is_empty()
def is_matched(s): left = '([{' right = ')]}' stack = ArrayStack() for c in s: if c in left: stack.push(c) elif c in right: if stack.is_empty(): return False elif left.index(stack.pop()) != right.index(c): return False return stack.is_empty()
def parentheses_match(expr): """ Return True if all delimiters are properly match; False otherwise.""" left = '({[' # opening delimiters right = ')}]' # respective closing delims S = ArrayStack() for c in expr: if c in left: S.push(c) # push left delimiter on stack elif c in right: if S.is_empty(): # nothing to match with return False if right.index(c) != left.index(S.pop()): return False # mismatched return S.is_empty() # were all symbols matched?
class SortedStack: def __init__(self): self._stack = ArrayStack() def peek(self): return self._stack.peek() def pop(self): return self._stack.pop() def push(self, value): temp = ArrayStack() if self._stack.is_empty() or self._stack.peek() > value: self._stack.push(value) else: hold = value size = len(self._stack) + 1 while len(self._stack) != size: if self.peek() < hold and self.peek() is not None: temp.push(self.pop()) elif hold is not None: self._stack.push(hold) hold = None else: self._stack.push(temp.pop())
class Queue: def __init__(self): self._in = ArrayStack() self._out = ArrayStack() def enqueue(self, e): self._in.push(e) def dequeue(self): if self._out.is_empty(): while not self._in.is_empty(): self._out.push(self._in.pop()) if self._out.is_empty(): raise Empty() return self._out.pop()
def InfixToPostfix(self, infixExpression): stackyStack = ArrayStack() stringPostfix = "" for character in infixExpression: if (character not in operator): stringPostfix += character elif stackyStack.is_empty(): stackyStack.push(character) else: stringPostfix += stackyStack.pop() stackyStack.push(character) while (not stackyStack.is_empty()): stringPostfix += stackyStack.pop() return stringPostfix
def main(): S = ArrayStack() print(len(S)) S.push(5) S.push(3) print(len(S)) print(S.pop()) print(S.is_empty()) print(S.pop()) print(S.is_empty()) S.push(7) S.push(9) print(S.top()) S.push(4) print(len(S)) print(S.pop()) S.push(6)
def is_matched(self, expr): """ Running time : O(n) :return: true if there are matching opening/closing symbols """ 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 checkHTML(raw_html): stack = ArrayStack() i = raw_html.find('<') # will return -1 if nothing found while i != -1: j = raw_html.find('>', i + 1) # find the index of the '>' if j == -1: return False tag = raw_html[i + 1:j] # get the tag name ex: <body> --> body if not tag.startswith('/'): stack.push(tag) # push opening tag onto stack else: if stack.is_empty(): # check if stack is empty return False if tag[1:] != stack.pop(): # check tag with tag on stack return False i = raw_html.find('<', j + 1) # find the index of the next tag return stack.is_empty()
def permutations(lst): perms = ArrayStack() parts = ArrayQueue() combo = [] for x in range(len(lst)): if perms.is_empty(): perms.push([lst[x]]) else: for y in range(len(perms)): p_lst = perms.pop() for z in range(len(p_lst) + 1): parts.enqueue(p_lst[:z] + [lst[x]] + p_lst[z:]) for a in range(len(parts)): perms.push(parts.dequeue()) while not perms.is_empty(): combo.append(perms.pop()) return combo
def is_matched(expr): """ >>> is_matched('((( )(( )){([( )])}))') True >>> is_matched(': )(( )){([( )])}') False """ 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 reverse_file(filename): S = ArrayStack() original = open(os.path.join(__location__, filename)) for line in original: S.push(line.rstrip('\n')) original.close() output = open(os.path.join(__location__, 'output.txt'), 'w') while not S.is_empty(): output.write(S.pop() + '\n') output.close()
def reverse_file(self, filename): S = ArrayStack() original = open(filename) for line in original: S.push(line) original.close() out = open(filename, 'w') while not S.is_empty(): out.write(S.pop() + '\n') out.close()
def is_matched_html(self, raw): """ :return: True if there are correct opening and closing html tags """ s = ArrayStack() j = raw.find('<') while j != -1: k = raw.find('>', j+1) if k == -1: return False tag = raw[j+1:k] # strip < > if not tag.startswith('/'): # opening tag 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 is_matched_html(raw): S = ArrayStack() j = raw.find('<') while j != -1: k = raw.find('>', j + 1) if k == -1: return False tag = raw[j + 1:k] print(tag) if not tag.startswith('/'): # its opening tag S.push(tag) else: # its ending tag if S.is_empty(): return False if tag[1:] != S.pop(): return False j = raw.find('<', k + 1) return S.is_empty()
def is_matched_html(raw): """ Returns true if all html tags are properly match, false otherwise """ s = ArrayStack() # '<h2>Hello world!</h2>' j = raw.find('<') while j != -1: k = raw.find('>', j+1) 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 preorder_with_stack(self): if (self.is_empty()): return DFS_stack = ArrayStack() DFS_stack.push(self.root) while (DFS_stack.is_empty() == False): curr_node = DFS_stack.pop() yield curr_node if (curr_node.right is not None): DFS_stack.push(curr_node.right) if (curr_node.left is not None): DFS_stack.push(curr_node.left)
def PostfixToPrefix(self, postfixExpression): stack = ArrayStack() stringPrefix = "" for x in range(0, len(postfixExpression)): if (postfixExpression[x] in operator): second = stack.pop() one = stack.pop() stack.push(postfixExpression[x]+one+second) else: stack.push(postfixExpression[x]) while (not stack.is_empty()): stringPrefix += stack.pop() return stringPrefix
def PostfixToPrefix(self, postfixExpression): stack = ArrayStack() stringPrefix = "" for x in range(0, len(postfixExpression)): if (postfixExpression[x] in operator): second = stack.pop() one = stack.pop() stack.push(postfixExpression[x] + one + second) else: stack.push(postfixExpression[x]) while (not stack.is_empty()): stringPrefix += stack.pop() return stringPrefix
def PostfixToInfix(self, postfixExpression): stack = ArrayStack() stringInfix = "" for x in range(0, len(postfixExpression)): if postfixExpression[x] not in operator: stack.push(postfixExpression[x]) else: op1 = stack.pop() op2 = stack.pop() stack.push(op1 + postfixExpression[x] + op2) while not stack.is_empty(): stringInfix += stack.pop() return stringInfix
def PostfixToInfix(self, postfixExpression): stack = ArrayStack() stringInfix = "" for x in range (0, len(postfixExpression)): if postfixExpression[x] not in operator: stack.push(postfixExpression[x]) else: op1 = stack.pop() op2 = stack.pop() stack.push(op1 + postfixExpression[x] + op2) while not stack.is_empty(): stringInfix += stack.pop() return stringInfix
def PrefixToPostfix(self, prefixExpression): stack = ArrayStack() stringPostfix = "" prefixExpression = prefixExpression[::-1] for x in range(0, len(prefixExpression)): if (prefixExpression[x] in operator): one = stack.pop() second = stack.pop() stack.push(one + second + prefixExpression[x]) else: stack.push(prefixExpression[x]) while (not stack.is_empty()): stringPostfix += stack.pop() return stringPostfix
def flatten_dll(dll): result = DoublyLinkedList() temp = ArrayStack() for elem in dll: temp.push(elem) while not temp.is_empty(): elem = temp.pop() if isinstance(elem, DoublyLinkedList): for sub_elem in elem: temp.push(sub_elem) else: result.add_first(elem) return result
def PrefixToPostfix(self, prefixExpression): stack = ArrayStack() stringPostfix = "" prefixExpression = prefixExpression[::-1] for x in range(0, len(prefixExpression)): if (prefixExpression[x] in operator): one = stack.pop() second = stack.pop() stack.push(one+second+prefixExpression[x]) else: stack.push(prefixExpression[x]) while (not stack.is_empty()): stringPostfix += stack.pop() return stringPostfix
class ReverseFile: def __init__(self): # 初始化一个栈对象 self.data_stack = ArrayStack() def read_file(self, filename): # 读入文本文件 original = open(filename) for line in original: self.data_stack.push(line.strip("\n")) original.close def reverse_data(self, filename): # 将栈中的元素逐个输出 output = open(filename, "w") while not self.data_stack.is_empty(): output.write(self.data_stack.pop() + "\n") output.close
class TestArrayStack(unittest.TestCase): def setUp(self): self.s = ArrayStack() self.s.push(1) self.s.push(2) def test_instantiation(self): print('Can create an instance') self.assertIsInstance(self.s, ArrayStack) def test_is_empty_method(self): print('Can check if the stack is empty') self.s.pop() self.s.pop() self.assertEqual(self.s.is_empty(), True) def test_push_method(self): print('Can add element to the top of the stack') self.s.push(5) self.assertEqual(self.s.top(), 5) def test_pop_method(self): print('Can remove element(s) from the top of the stack') self.assertEqual(self.s.pop(), 2) self.assertEqual(self.s.top(), 1) def test_length_checking(self): print('Can check the length of the stack') self.assertEqual(len(self.s), 2) def test_exception_raising(self): print('Can raise exception while performing action(s) on empty stack') self.s.pop() self.s.pop() with self.assertRaises(Empty): self.s.top() self.s.pop()
"""Using the ArrayStack object to reverse a string""" from ArrayStack import ArrayStack forward = "Never odd or even" reverse = "" stack = ArrayStack() for char in forward: stack.push(char) while not stack.is_empty(): reverse += str(stack.pop()) print(forward) print(reverse)
run_lst = [] block_lst = [] job_is_running_time = 0 # to calc cpu utilization job_is_blocking_time = 0 # to calc i/o utilization if detailed_mode: print( "\nThis detailed printout gives the state and remaining burst for each process.\n" ) while job_incomplete > 0: # one time unit is one cycle if detailed_mode: cycle_report(time, jobs_lst) # scan status for change scan_job(S, jobs_lst, time) if not S.is_empty() and cpu_can_run: cur_job = S.pop() cur_job.start_run() job_running_in_cur_cycle = False job_is_blocking_in_cur_cycle = False for j in jobs_lst: if j.get_state() == 'running': j.run_controller() job_running_in_cur_cycle = True elif j.get_state() == 'blocked': j.block_controller() job_is_blocking_in_cur_cycle = True elif j.get_state() == 'ready': j.increment_waiting_time()