예제 #1
0
def demonstrate_min_stack():
    minstack = MinStackADT()

    numbers = input_array()
    for num in numbers:
        minstack.push(num)

    while minstack.size() != 0:
        print(minstack.min())
        minstack.pop()
예제 #2
0
def input_matrix(prompt="arr : ") -> List[List[int]]:
    """
    Jagged Array Is Possible : https://en.wikipedia.org/wiki/Jagged_array
    Notice : you need to be careful, on the no of columns you are putting
    """
    row = int(input("rows :"))

    matrix = []
    for _ in range(row):
        row = input_array(prompt)
        matrix.append(row)
    return matrix
예제 #3
0
def input_linked_list() -> Node:
    """
    In our case, we do not need -1 to stop taking input
    """
    linked_list_data = input_array()

    temporary_node = Node(-9999999)
    head = tail = temporary_node  # To get rid off null check on head, in the loop

    # tail : will work as the moving_pointer
    for data in linked_list_data:
        new_node = Node(data)
        tail.next = new_node
        tail = tail.next

    return head.next  # passing over the temporary_node
예제 #4
0
    def input_interactive() -> GenericTreeNode:
        """
        2                              2
        3                           /  |  \
        3 4 0                     /    |    \
        2                       /      |     \
        5 6                   3        4        0
        2                   5  6     7  8
        7 8                9        1
        0
        1
        9
        0
        1
        1
        0
        0
        0
        """
        root_value = int(input("Enter Root : "))
        if root_value == -1:  # Creating a empty tree - ie None
            return None

        root_node = GenericTreeNode(root_value)

        queue = deque()  # push at end, pop from front
        queue.append(root_node)

        while len(queue) != 0:  # queue is not empty
            curr_root = queue.popleft()

            print(curr_root.data, "'s child count : ", end="")
            child_count = int(input())
            if child_count == 0:
                continue

            print("Children of " + str(curr_root.data))
            children = input_array()
            for child in children:
                child_node = GenericTreeNode(child)
                curr_root.children.append(child_node)
                queue.append(child_node)

        return root_node  # The original root, Not modified
예제 #5
0
def input_linked_list_with_end_value(end_of_linked_list=-1) -> Node:
    """
    Here to end the linked list input, end_of_linked_list value is required
    By default the end_of_linked_list value is -1
    """
    linked_list_data = input_array("LL :")

    temporary_node = Node(-9999999)
    head = tail = temporary_node  # To get rid off null check on head, in the loop

    # tail : will work as the moving_pointer
    for data in linked_list_data:
        if data == end_of_linked_list:
            break
        new_node = Node(data)
        tail.next = new_node
        tail = tail.next

    return head.next  # passing over the temporary_node
    # both root should have same data and same no of childerns
    if root_a.data != root_b.data or \
            len(root_a.children) != len(root_b.children):
        return False

    children_count = len(root_b.children)  # or len(root_a.children)
    for i in range(children_count):
        child_a = root_a.children[i]
        child_b = root_b.children[i]
        identical = is_structurally_identical(child_a, child_b)
        if not identical:
            return False  # else keep on checking for other children pairs

    return True  # if not yet returned


if __name__ == "__main__":
    tree_root_a = GenericTree.single_line_input(input_array())
    tree_root_b = GenericTree.single_line_input(input_array())
    print(is_structurally_identical(tree_root_a, tree_root_b))

"""
10 3 20 30 40 2 40 50 0 0 0 0 
10 3 20 30 40 2 40 50 0 0 0 0
True <<< Output

10 3 20 30 40 2 40 50 0 0 0 0 
10 3 2 30 40 2 40 50 0 0 0 0
False <<< Output
"""
예제 #7
0
    return final_sorted_arr


def sort_array(arr) -> list:
    if arr is None:  # Edge case
        print("Invalid Input")
        return []

    if len(arr) == 1 or len(
            arr) == 0:  # Base Case - Single Element Array Is Inherently Sorted
        return arr

    last_num = arr.pop()  # Decreasing the input
    sorted_array = sort_array(
        arr)  # Here it is of one less size, then our original problem

    # Induction step : need to insert the last_num in the sorted_array, to fully sort current array A - Insertion Sort
    full_size_sorted_array = insert_num_iteratively(sorted_array, last_num)
    # full_size_sorted_array = insert_num_iteratively__using_binary_search(sorted_array, last_num)
    return full_size_sorted_array


if __name__ == "__main__":
    print(sort_array(input_array()))
"""
5 6 3 4 2 1 0
1 2 3 4 5
5 4 2 0 -1
"""
예제 #8
0
    global diameter  # Update diameter, when curr_diameter > left + right depth
    diameter = max(diameter, left_depth + right_depth)  # Notice

    return max(left_depth, right_depth) + 1  # maximum_depth


def diameter_of_binary_tree(root: BinaryTreeNode) -> int:
    find_depth(
        root
    )  # basically find the diameter when we are processing the tree for finding depth
    return diameter


if __name__ == "__main__":
    tree_input = input_array()
    tree_root = BinaryTree.single_line_input(tree_input)
    BinaryTree.display(tree_root)
    print("diameter : ", diameter_of_binary_tree(tree_root))
"""
            1
          /   \
        2      3
      /  \
    4     5
    
1 2 3 4 5 -1 -1 -1 -1 -1 -1
"""
"""
          0
         / \ 
예제 #9
0
def find_water(arr) -> int:
    n = len(arr)
    maxL = find_maximum_left_for_each(arr, n)
    maxR = find_maximum_right_for_each(arr, n)

    water_at_each_building = [
        min(left_tall_building, right_tall_building) - curr_building_height
        for left_tall_building, right_tall_building, curr_building_height in
        zip(maxL, maxR, arr)
    ]

    total_water = sum(water_at_each_building)
    return total_water

    # print(maxL)
    # print(maxR)
    # print(water_at_each_building)


if __name__ == "__main__":
    building_heights = input_array(
    )  # A non-negative array, as these are buildings height
    water = find_water(building_heights)
    print(water)
"""
3 0 0 2 0 4  => 10
0 1 0 2 1 0 1 3 2 1 2 1  =>  6
2 0 2  =>  2
3 0 2 0 4  =>  7
"""
예제 #10
0
               dollar
      *70 /       |*0.8   \*0.9
     rs.        pound     euro
   |       |      
   |*2      |  * 0.04
  xyz       dinar  
   

dinar 40  -> xyz              dollar to dinar                      then               dollar to xyz
                             70 * 0.04   --> total multiplier                          70 * 2
              

Time
O(n) for tree traversal
O(M) to answer all the M queries
total = O(m + n)


Space 
O(n) space for mapi  : so that we can answer our M queriey in o(1) time



M Times
current_currency   amount       conversion_Currency
"""

if __name__ == "__main__":
    input_array()
    pass
예제 #11
0
from Stack.Aditya_Verma.Index__Greater_n_Smaller_Nums_To_Left_n_Right.NGL_Index import \
    indexes_of_next_greater_element_to_left
from Utils.Array import input_array


# You can remove the first two if's, that will work too
# Optimized stack solution
# O(n) Time
# O(n) Space
def get_result_array(ngl_index_array):
    length = len(ngl_index_array)
    res = [-1] * length

    for i in range(0, length):
        res[i] = i - ngl_index_array[i]

    return res


if __name__ == "__main__":
    arr = input_array()
    ngl_index_array = indexes_of_next_greater_element_to_left(arr)
    print(get_result_array(ngl_index_array))
"""
10 5 11 10 20 12
100 80 60 70 60 75 85
"""
예제 #12
0
        elif stack[-1][0] < curr:  # stack_top < curr element       Notice : compare-value
            result[i] = stack[-1][1]  # result is stack_top         Notice : insert-index

        elif stack[-1][0] >= curr:  # stack_top >= curr element     Notice : compare-value
            while len(stack) != 0 and stack[-1][0] >= curr:  # Notice : compare-value
                stack.pop()  # pop all elements greater then equal to curr, until the stack is empty

            # By which of the above condition, the loop has ended
            if len(stack) == 0:
                result[i] = -1  # result is -1      <similar to our 1st condition>
            else:  # found an element smaller then curr_element
                result[i] = stack[-1][1]  # result is stack_top   <similar to our 2nd condition> Notice : insert-index

        # Handled the current element, We have processed it
        stack.append((curr, i))  # Notice  0: value, 1: index

    return result


if __name__ == "__main__":
    buildings = input_array()
    indexes = indexes_of_next_smaller_element_to_right(buildings)
    print(indexes)

"""
6 2 5 4 5 1 6

[1, 5, 3, 5, 5, -1, -1]
"""
예제 #13
0
def segregate_negatives_and_positive__2pass(arr):
    n = len(arr)

    another_arr = [None] * n  # empty list of similar size
    left = 0

    for num in arr:
        if num < 0:
            another_arr[left] = num
            left += 1

    for num in arr:
        if num >= 0:
            another_arr[left] = num
            left += 1

    # copy back to the original array
    for i in range(0, n):
        arr[i] = another_arr[i]


if __name__ == "__main__":
    array = input_array()
    segregate_negatives_and_positive__2pass(array)
    print(array)
"""
-1  2  -3   4   5   6  -7   8  9
 2  3  -1  -4  -6                           # Reverse
 4  3   2   1   0  -1  -2  -3               # Reverse containing 0
"""
예제 #14
0
    for n in nums:
        if n < first_smallest:
            second_smallest = first_smallest
            first_smallest = n
        elif n < second_smallest and n != first_smallest:  # To handle duplicate cases
            second_smallest = n

    if second_smallest == float("inf"):
        print("There was no second smallest")
        return first_smallest, None
    else:
        return first_smallest, second_smallest


if __name__ == "__main__":
    array = input_array("List of integer numbers : ")
    first, second = find_first_and_second_smallest(array)
    print(first, second)

"""
------- Test cases ------- 

12 13 2 11 0 10
1 2 3 4 5 6 7
7 7 7 7 7 7 7       Imp
3 2 2 1 1 2 3       v.v.v Imp   basically duplicate first and second smallest   
                    Need special condition otherwise both first and second will be same ie, 1, 1

"""
# Not Inplace
def prefix_sum(array) -> list:
    arr = [num for num in array]  # making a copy of actual_array    # Notice : only change

    for i in range(1, len(array)):  # From 1 to n-1
        arr[i] = arr[i] + arr[i - 1]

    return arr


# Via Itertools
def prefix_sum_via_itertools(array):
    rolling_sum = itertools.accumulate(array, operator.add)
    print(type(rolling_sum))
    return list(rolling_sum)


if __name__ == "__main__":
    given_array = input_array()
    print_array_inline(prefix_sum(given_array))
    print_array_inline(prefix_sum_via_itertools(given_array))

"""
Input : 6 3 -2 4 -1 0 -5
Result: 6 9 7 11 10 10 5

Input : 2 1 -2 4 8
Result: 2 3 1 5 13

"""
예제 #16
0
        else:
            C.append(B[b])
            b += 1

    # if B is exhausted then put all the elements of A
    while a < len(A):
        C.append(A[a])
        a += 1

    # if A is exhausted then put all the elements of B
    while b < len(B):
        C.append(B[b])
        b += 1

    return C


if __name__ == "__main__":
    arrA = input_array()
    arrB = input_array()
    arr = merge_2_sorted_arrays(arrA, arrB)
    print_array_inline(arr)

"""
arrA = 1  3  5  7  9
arrB = 0  2  4  6  8

arrA =  1  1  5  5  10
arrB = -1  0  0  1   1  8
"""
예제 #17
0
from Binary_Search.Aditya_Verma.First_n_Last_Occurrence_In_Sorted_Array.First_Occurrence_In_Sorted_Array import \
    first_occurrence_in_sorted_array
from Binary_Search.Aditya_Verma.First_n_Last_Occurrence_In_Sorted_Array.Last_Occurrence_In_Sorted_Array import \
    last_occurrence_in_sorted_array
from Utils.Array import input_array

if __name__ == "__main__":
    array = input_array()  # Expected sorted array
    search_key = int(input())
    first_index = first_occurrence_in_sorted_array(array, search_key)
    last_index = last_occurrence_in_sorted_array(array, search_key)

    print("{} \nKey : {} \nFirst Index : {} \nFirst Index : {}".format(
        array, search_key, first_index, last_index))
"""
[]      # Just put ENTER
1

[1]
1

1 1 1 1 1
1


1 2 2 2 4 5 6 7 8 9 10
2


1 3 5 5 5 5 67 123 125
5
    while i < len(arrivals) and j < len(
            departures
    ):  # Lengths of both array is same : Read the above concept ^^^^
        if arrivals[i] < departures[j]:
            platforms_required += 1
            i += 1
        else:  # departures[j] < arrivals[i]
            platforms_required -= 1
            j += 1

        max_platforms = max(platforms_required, max_platforms)

    return max_platforms


if __name__ == "__main__":
    arrival_times = input_array()
    departure_times = input_array()
    min_platforms = minimum_platforms(arrival_times, departure_times)
    print(min_platforms)
"""
arrival   = [0900 0940 0950 1100 1500 1800]
departure = [0910 1200 1120 1130 1900 2000]
3 

arrival   = [900  940] 
departure = [910  1200]
1
"""
예제 #19
0
        dp[items][capacity] = profit_after_NOT_choosing_curr_item
        return dp[items][capacity]


def solve_01knapsack(weight, value, capacity):
    if len(weight) != len(value):
        raise ValueError("Invalid Item array")

    dp = get_filled_matrix(row_size=len(weight) + 1,
                           col_size=capacity + 1,
                           fill=-1)
    return max_profit_in_01knapsack(weight, value, capacity, dp)


if __name__ == "__main__":
    wt = input_array()
    val = input_array()
    c = int(input("capacity : "))
    print(solve_01knapsack(wt, val, c))
"""
wt  = 1 3 4 5
val = 1 4 5 7
c  =  7

wt  = 4 5 1
val = 1 2 3
c  =  4

wt  = 4 5 1
val = 1 2 3
c  =  3
예제 #20
0
from Utils.Array import input_array
"""
Given a list of x,y
can you tell if all these points lie on the same line
"""


def verify_straight_line(xy) -> bool:
    slopes = set()
    first_point_slope = xy[0][1] / xy[0][0]
    slopes.add(first_point_slope)
    for i in range(1, len(xy)):
        point = xy[i]
        slope = point[1] / point[0]
        if slope not in slopes:
            return False
    return True


if __name__ == "__main__":
    x_s = input_array()
    y_s = input_array()
    xy = [xy for xy in zip(x_s, y_s)]

    print(verify_straight_line(xy))
"""
1 2 3
1 2 3
"""
예제 #21
0
    finding_x_for_each_node__pre_order(root.left, x_table,
                                       horizontal_distance - 1)
    finding_x_for_each_node__pre_order(root.right, x_table,
                                       horizontal_distance + 1)


def vertical_order(root):
    x_table: Dict[int, list] = dict()  # map of number, list
    finding_x_for_each_node__pre_order(root, x_table)

    for x in sorted(x_table.keys()):
        print_array_inline(x_table[x])


if __name__ == "__main__":
    tree_root = BinaryTree.single_line_input(input_array())
    BinaryTree.display(tree_root)
    vertical_order(tree_root)
"""
                       1
                      / \
                     2   3
                    / \   \
                   4   5   6
                  /     \
                 7       8   
1 2 3 4 5 -1 6 7 -1 -1 8 -1 -1 -1 -1 -1 -1

Output
7
4
예제 #22
0
        if curr_root is None or curr_root_state == 3:
            # curr_root is popped out of the stack, and not pushed
            continue

        stack.append((curr_root, curr_root_state + 1))  # pushed curr_root with updated state

        if curr_root_state == 0:
            stack.append((curr_root.left, 0))
        elif curr_root_state == 1:
            stack.append((curr_root.right, 0))
        elif curr_root_state == 2:
            print(curr_root.data, end=" ")


if __name__ == "__main__":
    tree_input = input_array(prompt="")
    tree_root = BinaryTree.single_line_input(tree_input)
    BinaryTree.display(tree_root)
    do_postorder_traversal(tree_root)
    print()
    do_postorder_traversal_iteratively(tree_root)

"""
                        1
                    2      3
                  4   5      6
                7      8   

1 2 3 4 5 -1 6 7 -1 -1 8 -1 -1 -1 -1 -1 -1  

"""
예제 #23
0
from Tree.GenericTree.GenericTree import GenericTree
from Utils.Array import input_array


def find_sum_of_all_nodes(root):
    if root is None:
        return 0  # no nodes, so sum is 0

    subtree_sum = 0
    for child in root.children:
        subtree_sum += find_sum_of_all_nodes(child)

    total_sum = subtree_sum + root.data
    return total_sum


if __name__ == "__main__":
    root = GenericTree.single_line_input(input_array())
    # GenericTree.print_level_order(root)
    print(find_sum_of_all_nodes(root))
"""
10 3 20 30 40 2 40 50 0 0 0 0
190
"""
예제 #24
0
    if k == 1:
        return arr[
            0]  # The first smallest will always be the 0th indexed element of the array
    else:
        k = k - 1  # Important Note : This is because we are skipping the 0th index
        # Start from the index 1, and to check the uniqueness we can compare it with its previous one
        # if unique will count it in the k (ie, k will decrease) else, we will skip it (ie, k will remain unchanged)

        for i in range(1, len(arr)):
            if arr[i] == arr[i - 1]:
                continue  # skipping, and not decreasing k
            else:  # arr[i] != arr[i - 1]:
                k = k - 1
                if k == 0:
                    return arr[i]


if __name__ == "__main__":
    array = input_array("Arr : ")
    k = int(input("k : "))
    print(kth_smallest_via_sorting(array, k))
    print(kth_smallest_via_sorting__handling_duplicity(array, k))
"""
12 3 5 7 19    k=2   - Random                                    Sorted:  3 5 7 12 19     Result : 5                                                                                                         
1 2 3 4 5 6    k=3   - Sorted                                    Sorted:  same            Result : 3
9 8 7 6 5 4    k=3   - Reverse Sorted                            Sorted:  4 5 6 7 8 9     Result : 6     
3 3 1 8 2 1    k=2   - Random with duplicates [Important]        Sorted:  1 1 2 3 3 8     Result : 1        Correct : 2 
                       Notice : Wrong Result - doesn't handle duplicity
                       To handle duplicity we would require to write more logic
"""