예제 #1
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
예제 #2
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
예제 #3
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