Пример #1
0
def subset_sum_k(k: int, input: list, output: list, index: int) -> None:
    # Base Case 1
    if k == 0:
        print_array_inline(output)  # Directly printing it  Notice
        return

    # Base Case 2
    if index >= len(input):  # Don't proceed further
        return

    curr_element = input[index]

    if curr_element <= k:  # Have both options, Include it & Excluding it
        # Excluding it
        output_when_excluding = list.copy(output)
        subset_sum_k(k, input, output_when_excluding,
                     index + 1)  # input, output changed, not k

        # Including It
        output_when_including = list.copy(output)
        output_when_including.append(curr_element)  # output, input & k changed
        subset_sum_k(k - curr_element, input, output_when_including, index + 1)

    else:  # Excluding it       if > k
        output_when_excluding = list.copy(output)
        subset_sum_k(k, input, output_when_excluding,
                     index + 1)  # input, output changed, not k
    pass
def vertical_order(root):
    x_table: Dict[int, list] = dict()  # map of number, list
    finding_x_for_each_node__level_order(root, x_table)

    # for x in sorted(x_table.keys()):                          <<<<<<<<<<<<< Removing sorting Notice
    #     print_array_inline(x_table[x])

    min_hd, max_hd = float("inf"), float("-inf")
    for key in x_table.keys():
        min_hd = min(min_hd, key)
        max_hd = max(max_hd, key)

    for i in range(min_hd, max_hd + 1):  # so that we include max_hd as well
        print_array_inline(x_table[i])
def sort_nearly_sorted_array(arr, k) -> None:
    sorted_arr = [
    ]  # we are not doing it Inplace, but can be done with a little more effor

    heap = []  # Empty Min-Heap
    heapify(heap)

    for element in arr:
        heappush(heap, element)
        if len(heap) > k:
            curr = heappop(heap)  # this is the first element of the
            sorted_arr.append(curr)

    # empty the heap
    while len(heap) != 0:
        curr = heappop(heap)  # this is the first element of the
        sorted_arr.append(curr)

    print_array_inline(sorted_arr)
Пример #4
0
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])
def frequency_sort(nums):
    freq = get_frequencies_in_integer_array(nums)

    # Instead of writing a comparison function, we will gonna use Heap, and heapify on the basis of freq
    # create an empty heap, (which underline is a list)
    heap = [
    ]  # We want to use it as a MaxHeap, so need to negate the value of freq, so that freq comes on top
    for number, frequency in freq.items():
        heappush(
            heap, (-frequency, number)
        )  # we put frequency first, as we are heapify-ing on the basis of freq
    # print(heap)

    freq_sorted_array = []
    while len(heap) != 0:
        frequency, number = heappop(heap)
        frequency *= -1  # Making Freq +ve Again
        for i in range(frequency):
            freq_sorted_array.append(number)

    return freq_sorted_array


if __name__ == "__main__":
    array = input_array()
    f_sorted_array = frequency_sort(array)
    print_array_inline(f_sorted_array)
"""
2 5 2 8 5 6 8 8 
"""
# 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

"""
Пример #7
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
"""
            # Sort B, by putting B[0] at its correct position in B, to maintain the sorted order of B.
            # Note: B[1 ... n-1] is already sorted
            for i in range(1, m):
                if B[i - 1] > B[i]:
                    B[i - 1], B[i] = B[i], B[i - 1]  # swap

            # sort the array B, as it might be distorted :
            # Using Insertion sort (as it will take O(n) only)       --> as the array is partially sorted only
            # Note : You can't just call insertion_sort algorithm, because that will assume all the elements un-sorted
            #  and will apply sorting on all of them, which will result in O(n^2) time,
            #  Instead ::: we should just sort this element only by putting it onto the correct location --> O(n) time


if __name__ == "__main__":
    arrA = input_array()
    arrB = input_array()
    merge_2_sorted_arrays_without_space(arrA, arrB)

    print_array_inline(arrA)
    print_array_inline(arrB)
"""
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

X = 1 4 7 8 10
Y = 2 3 9
"""
Пример #9
0
    # Induction
    if nums[n - 1] == key:  # last element is similar to key
        all_indices.append(n - 1)


def find_index_of_all_occurrence__backward(nums, key) -> List[int]:
    all_indices = []
    find_all_occurrence__backward(nums, key, len(nums), all_indices)
    return all_indices


if __name__ == "__main__":
    setrecursionlimit(11000)
    n = int(input())
    arr = list(int(i) for i in input().strip().split(' '))
    x = int(input())

    print_array_inline(find_index_of_all_occurrence__forward(arr, x))
    print_array_inline(find_index_of_all_occurrence__backward(arr, x))
'''
4
9 8 10 8
8


5
9 8 10 8 8
8
'''
def vertical_order(root):
    x_y_table: Dict[int, list] = dict()  # map of number, list
    pre_order__to__fill_x_y_for_each_node(root, x_y_table)

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