예제 #1
0
class MyQueue:
    def __init__(self):
        self.front = Stack()
        self.end = Stack()

    def size(self):
        return self.front.size() + self.end.size()

    def enqueue(self, val):
        self.end.push(val)

    def dequeue(self):
        if self.front.is_empty() and not self.move():
            raise Exception("queue is empty")
        return self.front.pop()

    def peek(self):
        if self.front.is_empty() and not self.move():
            raise Exception("queue is empty")
        return self.front.peek()

    # time: O(n), however, the average is O(1)
    def move(self):
        moved = False
        while not self.end.is_empty():
            moved = True
            self.front.push(self.end.pop())
        return moved

    def print_q(self):
        print self.front
        print self.end
예제 #2
0
파일: chap_03.py 프로젝트: embatbr/ctci
    def version_2(test):
        (given, expected) = test

        original_stack = Stack()
        sorted_stack = Stack()

        for g in given:
            original_stack.push(g)

        # starts here

        num_eltos = original_stack.size

        for i in range(num_eltos):
            pivot = original_stack.pop()

            num_swaps = 0
            while (not sorted_stack.is_empty()) and (pivot < sorted_stack.peek()):
                original_stack.push(sorted_stack.pop())
                num_swaps += 1
            sorted_stack.push(pivot)

            for _ in range(num_swaps):
                sorted_stack.push(original_stack.pop())

        # sorts in reverse order (smallest on top)
        while not sorted_stack.is_empty():
            original_stack.push(sorted_stack.pop())

        given_str = ''.join(original_stack.to_array()) # doesn't count in the O(.) calculation
        return given_str == expected
예제 #3
0
def sort_stack(stack):
    buf = Stack()
    while not stack.is_empty():
        cur = stack.pop()
        cnt = 0
        while not buf.is_empty() and cur < buf.peek():
            stack.push(buf.pop())
            cnt += 1
        buf.push(cur)
        for i in xrange(cnt):
            buf.push(stack.pop())
    while not buf.is_empty():
        stack.push(buf.pop())
예제 #4
0
def sort_stack(stack):

    s1 = stack
    s2 = Stack(s1.size)

    while(s1.is_empty() != True):
        temp = s1.pop()
        while(s2.is_empty() != True and s2.peek() > temp):
            s1.push(s2.pop())
        s2.push(temp)

    return s2
예제 #5
0
파일: chap_03.py 프로젝트: embatbr/ctci
    def version_1(test):
        forward_stack = Stack()
        backward_stack = Stack()

        for t in test:
            forward_stack.push(t)

        while not forward_stack.is_empty():
            backward_stack.push(forward_stack.pop())

        result = ''.join(backward_stack.to_array())

        return test == result
예제 #6
0
파일: chap_03.py 프로젝트: embatbr/ctci
    def version_1(test):
        (given, expected) = test

        original_stack = Stack()
        sorted_stack = Stack()

        for g in given:
            original_stack.push(g)

        # starts here

        while not original_stack.is_empty():
            pivot = original_stack.pop()

            while (not sorted_stack.is_empty()) and (pivot < sorted_stack.peek()):
                original_stack.push(sorted_stack.pop())
            sorted_stack.push(pivot)

        # sorts in reverse order (smallest on top)
        while not sorted_stack.is_empty():
            original_stack.push(sorted_stack.pop())

        given_str = ''.join(original_stack.to_array()) # doesn't count in the O(.) calculation
        return given_str == expected
def quick_sort_by_stack3(A, p, r):
    stack = Stack()
    q, t = random_partition3(A, p, r)
    if q > p + 1:
        stack.push(p)
        stack.push(q - 1)
    if t < r - 1:
        stack.push(t + 1)
        stack.push(r)
    while not stack.is_empty():
        r = stack.pop()
        p = stack.pop()
        q, t = random_partition3(A, p, r)
        if q > p + 1:
            stack.push(p)
            stack.push(q - 1)
        if t < r - 1:
            stack.push(t + 1)
            stack.push(r)
예제 #8
0
class DbSession(object):
    """Provides an API for users to make changes to an in-memory database with transactions.

    Attributes:
        database: An instance of an in-memory database.
        transaction_stack: A stack of active transactions.
        current_trans: The currently active transaction. Transactions are a set of keys which
            represent keys in the database that have been edited during the current transaction.
    """
    def __init__(self):
        self.database = InMemoryDatabase()
        self.transaction_stack = Stack()
        self.current_trans = None
        self.reset_transaction_state()

    def reset_transaction_state(self):
        self.current_trans = set() if self.transaction_stack.is_empty(
        ) else self.transaction_stack.current()
        # Transaction stack should always have a 'base' transaction which can't be rolled back/commited
        self.transaction_stack = Stack(self.current_trans)

    def pop_transaction(self):
        self.transaction_stack.pop()
        self.current_trans = self.transaction_stack.current()

    def has_open_transaction(self):
        return self.transaction_stack.size() > 1

    def begin(self):
        self.current_trans = set()
        self.transaction_stack.push(self.current_trans)

    def rollback(self):
        if not self.has_open_transaction():
            print('NO TRANSACTION')
        else:
            map(self.database.remove, list(self.current_trans))
            self.pop_transaction()

    def commit(self):
        if not self.has_open_transaction():
            print('NO TRANSACTION')
        else:
            self.database.flatten()
            self.reset_transaction_state()

    def set_var(self, var, value):
        if var in self.current_trans:
            self.database.change(var, value)
        else:
            self.database.add(var, value)
            self.current_trans.add(var)

    def unset_var(self, var):
        self.set_var(var, None)

    def get_var(self, var):
        print(self.database.get(var) or 'NULL')

    def num_equal_to(self, value):
        print(self.database.num_equal_to(value))

    def __repr__(self):
        return '{}\nTransaction Stack: {}'.format(self.database,
                                                  self.transaction_stack)
예제 #9
0
class DbSession(object):
    """Provides an API for users to make changes to an in-memory database with transactions.

    Attributes:
        database: An instance of an in-memory database.
        transaction_stack: A stack of active transactions.
        current_trans: The currently active transaction. Transactions are a set of keys which
            represent keys in the database that have been edited during the current transaction.
    """
    def __init__(self):
        self.database = InMemoryDatabase()
        self.transaction_stack = Stack()
        self.current_trans = None
        self.reset_transaction_state()
    
    def reset_transaction_state(self):
        self.current_trans = set() if self.transaction_stack.is_empty() else self.transaction_stack.current()
        # Transaction stack should always have a 'base' transaction which can't be rolled back/commited
        self.transaction_stack = Stack(self.current_trans)
        
    def pop_transaction(self):
        self.transaction_stack.pop()
        self.current_trans = self.transaction_stack.current()

    def has_open_transaction(self):
        return self.transaction_stack.size() > 1
        
    def begin(self):
        self.current_trans = set()
        self.transaction_stack.push(self.current_trans)
        
    def rollback(self):
        if not self.has_open_transaction():
            print('NO TRANSACTION')
        else:
            map(self.database.remove, list(self.current_trans))
            self.pop_transaction()
        
    def commit(self):
        if not self.has_open_transaction():
            print('NO TRANSACTION')
        else:
            self.database.flatten()
            self.reset_transaction_state()

    def set_var(self, var, value):
        if var in self.current_trans:
            self.database.change(var, value)
        else:
            self.database.add(var, value)
            self.current_trans.add(var)
    
    def unset_var(self, var):
        self.set_var(var, None)
            
    def get_var(self, var):
        print(self.database.get(var) or 'NULL')
    
    def num_equal_to(self, value):
        print(self.database.num_equal_to(value))

    def __repr__(self):
        return '{}\nTransaction Stack: {}'.format(self.database, self.transaction_stack)
예제 #10
0
    def build(self, tree, X, y):

        init_capacity = 0
        if tree.max_depth <= 10:
            init_capacity = (2**(tree.max_depth + 1)) - 1
        else:
            init_capacity = 2047

        tree._resize(init_capacity)

        splitter = self.splitter
        max_depth = self.max_depth
        min_samples_leaf = self.min_samples_leaf
        min_samples_split = self.min_samples_split
        min_impurity_decrease = self.min_impurity_decrease
        min_impurity_split = self.min_impurity_split

        splitter.init(X, y)
        n_node_samples = splitter.n_samples

        # SplitRecord split
        impurity = np.inf
        first = 1
        max_depth_seen = -1
        rc = 0
        stack = Stack()
        # stack_record

        # node = StackRecord()
        # node.start = 0
        # node.end = n_node_samples
        # node.depth = 0
        # node.parent = _TREE_UNDEFINED
        # node.is_left = 0
        # node.impurity = np.inf
        # node.n_constant_features = 0

        stack.push(0, n_node_samples, 0, _TREE_UNDEFINED, 0, np.inf, 0)
        while not stack.is_empty() > 0:
            node = stack.pop()

            start = node.start
            end = node.end
            is_left = node.is_left
            is_leaf = node.is_leaf
            depth = node.depth

            n_node_samples = node.end - node.start
            splitter.node_reset(node.start, node.end)

            is_leaf = (node.depth >= max_depth
                       or n_node_samples < min_samples_split
                       or n_node_samples < 2 * min_samples_leaf)

            if first:
                impurity = splitter.node_impurity()
                first = 0
            is_leaf = (is_leaf or (impurity <= min_impurity_split))

            if not is_leaf:
                split, n_constant_features = splitter.node_split(impurity)
                is_leaf = (
                    is_leaf or split.pos >= node.end
                    or (split.improvement + EPSILON < min_impurity_decrease))

            node_id = tree._add_node(node.parent, node.is_left, is_leaf,
                                     split.feature, split.threshold,
                                     node.impurity, n_node_samples)

            splitter.node_value(tree.value + node_id * tree.value_stride)

            if not is_leaf:
                stack.push(split.pos, end, depth + 1, node_id, 0,
                           split.impurity_right, n_constant_features)
                stack.push(start, split.pos, depth + 1, node_id, 1,
                           split.impurity_left, n_constant_features)
            if depth > max_depth_seen:
                max_depth_seen = depth

            tree.max_depth = max_depth_seen