def main(): print "\ncheck stack" stack = Stack(1, 2, 34, 5) for x in range(0, 5): stack.push(x) print stack for x in range(0, 15): print "".join(["size=", str(len(stack)), " cur_node=", str(stack.pop())]) print "\ncheck queue" queue = Queue(1, 2, 34, 5) for x in range(0, 5): queue.enter(x) print stack for x in range(0, 15): print "".join(["size=", str(len(queue)), " cur_node=", str(queue.exit())]) print "\ncheck BSTree" tree = BSTree(1, 2, 34, 5) print tree print tree.find(10) print tree.find(5) print tree.max() print tree.min() print tree.successor(34) print tree.successor(5) print tree.predecessor(1) print tree.predecessor(2)
def test_constructs(self): s = Stack() s1 = Slice(1, 2, 3) s.push(s1) assert s[0] == s1 assert isinstance(s[0], Slice) assert s[0].__str__() == '1,2,3 R0'
def brackets_match(string): """Check if all brackets in the string are correctly matched. Return True if they are, otherwise False. Only consider round and square brackets, i.e. () and []. For example: >>> brackets_match("No brackets is fine") True >>> brackets_match("After ( and [ comes ] and )") True >>> brackets_match("After ( and [ it cannot be ) and ]") False >>> brackets_match("A ( without closing bracket") False >>> brackets_match("A ] without opening bracket") False >>> brackets_match("Snarks are rarely seen (according to Smith (1999)).") True """ expected = Stack() for character in string: if character == "(": expected.push(")") elif character == "[": expected.push("]") elif character == ")" or character == "]": if expected and character == expected.top(): expected.pop() else: return False return expected.is_empty()
def init_stacks(size): left = Stack() middle = Stack() right = Stack() for item in range(1, size + 1): left.push(item) return (left, middle, right)
def test_stack_reversed(self): stk = Stack() random_values = get_random_values() for v in random_values: stk.push(v) reversed_stk = reversed(stk) for v in random_values: self.assertEqual(reversed_stk.peek(), v) reversed_stk.pop() self.assertEqual(stk.size(), len(random_values))
def test_stack_is_empty(self): stk = Stack() random_values = get_random_values() self.assertEqual(stk.is_empty(), True) for v in random_values: stk.push(v) self.assertEqual(stk.is_empty(), False) for v in random_values[::-1]: self.assertEqual(stk.is_empty(), False) stk.pop() self.assertEqual(stk.is_empty(), True)
def test_stack_reverse(self): stk = Stack() random_values = get_random_values() for v in random_values: stk.push(v) stk.reverse() for v in random_values: self.assertEqual(stk.peek(), v) stk.pop()
def remove_even(self): tstack = Stack() # empty the stack and store even numbers in # another, temporary stack (in reverse order) while not self.empty: popped = self.pop() if popped % 2 == 1: tstack.push(popped) # move the data from temporary stack back to original while not tstack.empty: self.push(tstack.pop())
def midorder(self, f): """ B树中序遍历 :param f: :return: """ result = [] stack = Stack() cur_node = self.__root if cur_node.is_leaf: return map(f, cur_node.keys) while True: if cur_node.is_leaf: # 到叶节点了,开始把叶节点的所有关键字都遍历掉 result.extend(map(f, cur_node.keys)) # 开始从栈中取元素,遍历下一个节点叶节点 if stack.empty(): return result cur_node, i = stack.pop() result.append(f(cur_node.keys[i])) if i < len(cur_node) - 1: stack.push((cur_node, i + 1)) cur_node = cur_node.childs[i + 1] else: stack.push((cur_node, 0)) cur_node = cur_node.childs[0] return result
def test_stack_reversed_with_override(self): self.assertEqual(list(reversed([123, 456])), [456, 123]) stk = Stack() random_values = get_random_values() for v in random_values: stk.push(v) reversed_stk = reversed(stk) for v in random_values: self.assertEqual(reversed_stk.peek(), v) reversed_stk.pop() self.assertEqual(stk.size(), len(random_values)) self.assertEqual(list(reversed([123, 456])), [456, 123])
def add_to_stack(domain, name, version, file_name, meta_path, stack_version): """ Add created package to stack and reference packages. <name> actual name of the package. <version> version of the package. <file_name> exact file_name of the package (versioned, architecture...). <meta_path> path to the stacks and other meta information related to package <stack_version> version of the stack to attach the package to. """ # get the meta_path from .gachetterc meta_path = meta_path if 'meta_path' not in env else env.meta_path stack = Stack(domain, stack_version, meta_path=meta_path) stack.add_package(name, version, file_name)
def quick(domain, stack_version, project_name, ref="origin/master", url=None, path_to_missile=None, debs_path=None, meta_path=None): """ One-command to build and add to stack a specific branch. Depends heavily on pre-configuration via config file. Package version are set from Git commit. <domain> domain where the stack will be registered to (some kind of type for stack). <stack_version> version of the stack to attach the package to. <project_name> name of the project. <branch> is the branch to actually checkout. <url> is the url of the repo in github. <path_to_missile> is the path to the missile file in the project that will be used by trebuchet to build packages. <debs_path> path to where the DEB package should be created into. <meta_path> path to the stacks and other meta information related to package """ # Get value for the project, complain otherwise meta_path = meta_path if 'meta_path' not in env else env.meta_path debs_path = debs_path if 'debs_path' not in env else env.debs_path url = url if "projects" not in env or project_name not in env.projects or 'url' not in env.projects[project_name] else env.projects[project_name]['url'] path_to_missile = path_to_missile if "projects" not in env or project_name not in env.projects or 'path_to_missile' not in env.projects[project_name] else env.projects[project_name]['path_to_missile'] if not meta_path or not debs_path: abort("Please specify a meta_path/debs_path or add it approprietly in a config file") if not url: abort("Please specify a url or add it approprietly in a config file: projects.%s.url" % project_name) name = project_name if ref is None else project_name+"_"+ref.replace("/", "-") # use existing stack only (create one manually) new_stack = Stack(domain, stack_version, meta_path=meta_path) if not new_stack.is_persisted(): abort("""Please create a new stack first, using: `gachette stack_create`""") # Checkout specific branch and build wc = WorkingCopy(name) wc.prepare_environment() wc.checkout_working_copy(url, ref) # set version based on the git commit suffix = "" if ref is None else ref.replace("/", "-") version = wc.get_version_from_git(suffix=suffix) wc.set_version(app=version, env=version, service=version) results = wc.build(debs_path, path_to_missile, trebuchet_bin=trebuchet_bin) print "results: ", results # TODO extract package build results properly for item in results: new_stack.add_package(item['name'], item['version'], item['file_name'])
def test_stack_init(self): stk = Stack() self.assertEqual(stk.size(), 0) self.assertEqual(stk.is_empty(), True) with self.assertRaises(IndexError): stk.pop() with self.assertRaises(IndexError): stk.peek()
def update_active_stack_next(self): if self.active_stack.size < self.capacity: return self.active_stack = Stack() self.stacks.append(self.active_stack) self.active_stack_index += 1
def test_stack_size(self): stk = Stack() random_values = get_random_values() for i, v in enumerate(random_values): stk.push(v) self.assertEqual(stk.size(), i + 1) for i in range(len(random_values)): stk.pop() self.assertEqual(stk.size(), len(random_values) - i - 1)
def test_stack_push(self): stk = Stack() random_values = get_random_values() for v in random_values: stk.push(v) self.assertEqual(stk.is_empty(), False) self.assertEqual(stk.peek(), v) self.assertEqual(stk.pop(), v)
def test_stack_peek(self): stk = Stack() random_values = get_random_values() for v in random_values: stk.push(v) for v in random_values[::-1]: self.assertEqual(stk.peek(), v) stk.pop()
def midorder(self, f): """ 中序遍历 :param f:访问一个节点的时候要对节点进行处理的函数 :return: """ result = [] stack = Stack(self.__root) cur_node = self.__root.left # 第一个阶段首先把所有树左边的节点放进栈里,这个时候并不遍历 # 第二个阶段的时候由于左节点遍历了之后,再遍历右节点 while not stack.empty() or cur_node is not self.Nil: # 第二个判断条件比较重要,因为如果根节点没有左子树,这个时候栈就是空的,会直接退出循环 if cur_node is not self.Nil: stack.push(cur_node) cur_node = cur_node.left else: cur_node = stack.pop() result.append(f(cur_node)) cur_node = cur_node.right return result
def test_peeking_at_stack_returns_last_item(): stack = Stack() stack.push(1) stack.push(2) stack.push(3) assert_equal(stack.peek(), 3)
def test_popping_from_stack_removes_item(): stack = Stack() stack.push(1) assert_equal(stack.empty(), False) assert_equal(stack.pop(), 1) assert_equal(stack.empty(), True)
def test_popping_from_stack_returns_last_item(): stack = Stack() stack.push(1) stack.push(2) stack.push(3) assert_equal(stack.pop(), 3)
def test_pushing_to_stack_adds_item_to_stack(): stack = Stack() assert_equal(stack.empty(), True) stack.push(1) assert_equal(stack.empty(), False) assert_equal(stack.peek(), 1)
def test_peeking_at_stack_does_not_remove_item(): stack = Stack() stack.push(1) assert_equal(stack.empty(), False) assert_equal(stack.peek(), 1) assert_equal(stack.empty(), False)
class SetOfStacks: def __init__(self, capacity): self.capacity = capacity self.stacks = [Stack()] self.active_stack_index = 0 self.active_stack = self.stacks[0] def update_active_stack_next(self): if self.active_stack.size < self.capacity: return self.active_stack = Stack() self.stacks.append(self.active_stack) self.active_stack_index += 1 def update_active_stack_prev(self): if self.active_stack.size > 0: return if self.active_stack_index == 0: return self.active_stack_index -= 1 self.active_stack = self.stacks[self.active_stack_index] self.update_active_stack_prev() def push(self, data): self.update_active_stack_next() self.active_stack.push(data) return data def pop(self): self.update_active_stack_prev() return self.active_stack.pop() def pop_at(self, index): stack = self.stacks[index] if stack: return stack.pop()
def dec_to_bin(dec): s = Stack() n = dec if n == 0: s.push(n % 2) n = n // 2 while n > 0: s.push(n % 2) n = n // 2 number = s.size() binary = '' for i in range(number): binary = binary + str(s.pop()) return binary
def dec_to_bin(dec): s = Stack() while(dec>0): s.push(dec%2) dec // 2 binary = 0 for i in range(s.size()): num = s.pop() binary += num*(10**s.size()) return binary
def sort_stack(stack): sorted_stack = stack stack = Stack() while not sorted_stack.is_empty(): stack.push(sorted_stack.pop()) while not stack.is_empty(): tmp = stack.pop() while not sorted_stack.is_empty() and sorted_stack.peek() < tmp: stack.push(sorted_stack.pop()) sorted_stack.push(tmp)
def dec_to_bin(dec): tmp = Stack() binary = "" while dec != 0: tmp.push(dec % 2) dec //= 2 while not tmp.isEmpty(): binary += str(tmp.pop()) return binary
def dec_to_bin2(dec): s = Stack() i = 0 for j in range(10000): if(dec // (2**j) == 0): i = j break binary = 0 for k in range(i): k = i - k if(dec % (2 ** k) // (2 ** (k-1)) == 1): s.push(1) else: s.push(0) for l in range(s.size()): binary += s.pop() * (10 ** l) return binary
def stack_create(domain, name, meta_path=None, from_stack=None): """ Create a new stack. From old one if specified. """ # get the meta_path from .gachetterc meta_path = meta_path if 'meta_path' not in env else env.meta_path if not meta_path: abort("Please specify a `meta_path` or use a config file to define it") new_stack = Stack(domain, name, meta_path=meta_path) if not new_stack.is_persisted(): if from_stack: old_stack = Stack(domain, from_stack, meta_path=meta_path) new_stack.clone_from(old_stack) else: new_stack.persist()
def base_converter(dec_number, base): digits = "0123456789ABCDEF" s = Stack() n = dec_number while n > 0: number = n % base if number > 9: s.push(digits[number]) else: s.push(n % base) n = n // base number = s.size() string = '' for i in range(number): string = string + str(s.pop()) return string
class MinStack: def __init__(self): self.mins = Stack() self.items = Stack() def push(self, item): min = self.mins.peek() if min == None or item < min: self.mins.push(item) return self.items.push(item) def pop(self): item = self.items.pop() if item == self.mins.peek(): self.mins.pop() return item def min(self): return self.mins.peek()
def test_stack_copy(self): stk = Stack() random_values = get_random_values() for v in random_values: stk.push(v) copied_stk = stk.copy() for v in random_values[::-1]: self.assertEqual(copied_stk.peek(), v) copied_stk.pop() self.assertEqual(stk.size(), len(random_values))
def preorder(self, f): result = [] stack = Stack(self.__root) while True: cur_node = stack.pop() # 栈中没有元素的时候就表示所有的元素都已经遍历完了 if cur_node is None: break result.append(f(cur_node.value)) if cur_node.left is not None: stack.push(cur_node.left) if cur_node.right is not None: stack.push(cur_node.right) return result
def base_converter(dec_number, base): digits = "0123456789ABCDEF" tmp = Stack() string = "" while dec_number != 0: tmp.push(dec_number % base) dec_number //= base while not tmp.isEmpty(): string += digits[tmp.pop()] return string
def dec_to_bin(dec): binary = '' s = Stack() while dec != 0: tmp = dec % 2 dec = dec // 2 s.push(tmp) while s.size() != 0: a = s.pop() binary += str(a) return binary
def dec_to_bin(dec): # Finish the function s=Stack() while dec!=0: s.push(dec%2) dec=dec//2 binary=[] while not s.isEmpty(): binary.append(s.pop()) return binary
def setUp(self): # Create stacks for the tests to use self.new = Stack() self.empty = Stack() self.empty.push('hi') self.empty.pop() # Don't add in ascending or descending order self.non_empty = Stack() self.non_empty.push(5) self.non_empty.push(2) self.non_empty.push(7) self.non_empty.push(2)
def base_converter(dec_number, base): digits = "0123456789ABCDEF" s=Stack() while dec_number!=0: s.push(digits[dec_number%base]) dec_number=dec_number//base string='' while not s.isEmpty(): string=string+s.pop() return string
def dfs(self, gray_func, black_func): """ 图的深度遍历 :param gray_func: :param black_func: :return: """ gray_list = [] black_list = [] # 初始化 for key in self.__dict.iterkeys(): key.start_time = None key.end_time = None key.set_white() # 开始遍历 counter = 0 for key in self.__dict.iterkeys(): if key.is_white(): dfs_stack = Stack() key.set_gray() key.start_time = counter counter += 1 dfs_stack.push(key) while not dfs_stack.empty(): cur_node = dfs_stack.pop() gray_list.append(gray_func(key)) for end_node in self.__dict[cur_node]: if end_node.is_white(): end_node.set_gray() end_node.start_time = counter counter += 1 dfs_stack.push(end_node) cur_node.set_black() black_list.append(black_func(cur_node)) cur_node.end_time = counter counter += 1 return gray_list, black_list
def midorder(self, f): result = [] stack = Stack(self.__root) cur_node = self.__root.left # 第一个阶段首先把所有树左边的节点放进栈里,这个时候并不遍历 # 第二个阶段的时候由于左节点遍历了之后,再遍历右节点 while not stack.empty() or cur_node is not None: # 第二个判断条件比较重要,因为如果根节点没有左子树,这个时候栈就是空的,会直接退出循环 if cur_node is not None: stack.push(cur_node) cur_node = cur_node.left else: cur_node = stack.pop() result.append(f(cur_node.value)) cur_node = cur_node.right return result
def base_converter(dec, base): binary = '' s = Stack() while dec != 0: if base > 16 or base < 2: #若base輸入值不符合範圍,輸出error return "error" tmp = dec % base dec = dec // base if tmp >= 10: d = tmp % 10 tmp = chr(65 + d) s.push(tmp) while s.size() != 0: a = s.pop() binary += str(a) return binary
def test_empty_returning_true_when_empty(): stack = Stack() assert_equal(stack.empty(), True)
def test_popping_from_empty_stack_raises_custom_error_message(): stack = Stack() assert_equal(stack.pop(), "Error: Stack is empty")
def test_peeking_at_empty_stack_returns_none(): stack = Stack() assert_equal(stack.peek(), None)
def test_empty_returning_false_when_not_empty(): stack = Stack() stack.push(1) assert_equal(stack.empty(), False)
def reverse(stack): rstack = Stack() while not stack.empty: rstack.push(stack.pop()) return rstack
def __init__(self): self.mins = Stack() self.items = Stack()