Пример #1
0
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)
Пример #2
0
Файл: 4.py Проект: mhluska/ctci5
def init_stacks(size):
  left   = Stack()
  middle = Stack()
  right  = Stack()

  for item in range(1, size + 1):
    left.push(item)

  return (left, middle, right)
Пример #3
0
    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())
Пример #4
0
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)
Пример #5
0
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'])
Пример #6
0
Файл: 3.py Проект: mhluska/ctci5
  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
Пример #7
0
 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
Пример #8
0
    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
Пример #9
0
 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
Пример #10
0
def test_peeking_at_stack_returns_last_item():
    stack = Stack()
    stack.push(1)
    stack.push(2)
    stack.push(3)

    assert_equal(stack.peek(), 3)
Пример #11
0
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)
Пример #12
0
def test_popping_from_stack_returns_last_item():
    stack = Stack()
    stack.push(1)
    stack.push(2)
    stack.push(3)

    assert_equal(stack.pop(), 3)
Пример #13
0
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)
Пример #14
0
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)
Пример #15
0
Файл: 3.py Проект: mhluska/ctci5
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()
Пример #16
0
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)
Пример #17
0
Файл: 2.py Проект: mhluska/ctci5
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()
Пример #18
0
 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
Пример #19
0
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()
Пример #20
0
    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
Пример #21
0
def test_empty_returning_true_when_empty():
    stack = Stack()

    assert_equal(stack.empty(), True)
Пример #22
0
def reverse(stack):
    rstack = Stack()
    while not stack.empty:
        rstack.push(stack.pop())
    return rstack
Пример #23
0
def test_popping_from_empty_stack_raises_custom_error_message():
    stack = Stack()

    assert_equal(stack.pop(), "Error: Stack is empty")
Пример #24
0
Файл: 2.py Проект: mhluska/ctci5
 def __init__(self):
   self.mins  = Stack()
   self.items = Stack()
Пример #25
0
def test_empty_returning_false_when_not_empty():
    stack = Stack()
    stack.push(1)

    assert_equal(stack.empty(), False)
Пример #26
0
def test_peeking_at_empty_stack_returns_none():
    stack = Stack()

    assert_equal(stack.peek(), None)