def generate_and_swap(n: int): '''Generates a list of size n and swaps two elements in the list, O(n)''' my_list = random_number_insertion(n) swap_random(my_list)
from insertion import random_number_insertion def print_to_screen(element, a_list): ''' Prints element and list to screen, O(n) time with n being the size of the list. It goes through the list two times, but since constants are removed the time is still O(n) ''' print(element) stringified_list = [str(i) for i in a_list] # Time complexity: O(n) print(", ".join(stringified_list)) # Time complexity: O(n) def display(a_list): '''displays list info, O(n^2)''' for element in a_list: print_to_screen(element, a_list) # O(n) display(random_number_insertion(5))
def swap(a_list, indices): index1, index2 = indices a_list[index1], a_list[index2] = a_list[index2], a_list[index1] def switch_random(a_list: list): '''Switches two random neighbor elements in a list, O(1)''' index = random_index(a_list) swap(a_list, (index, index - 1)) def swap_random(a_list: list): '''Swaps two random elements in a list, O(1)''' indices = random_index_tuple(a_list) swap(a_list, indices) def generate_and_swap(n: int): '''Generates a list of size n and swaps two elements in the list, O(n)''' my_list = random_number_insertion(n) swap_random(my_list) if __name__ == "__main__": my_list = random_number_insertion(10) print(my_list) swap(my_list) print(my_list)
'''Single insert using binary search, still in O(n) time because of the insert.''' index = binary_search(a_list, number) insert(a_list, number, index) def test_insert(insert_function, a_list): '''Populates sorted list, complexity: O(n^2)''' my_list = list() for num in a_list: insert_function(my_list, num) return my_list if __name__ == "__main__": testlist = random_number_insertion(1000) start_time = timeit.default_timer() sorted_list_1 = test_insert(linear_insert, testlist) print(timeit.default_timer() - start_time) start_time = timeit.default_timer() sorted_list_2 = test_insert(binary_insert, testlist) print(timeit.default_timer() - start_time) for i, item in enumerate(zip(sorted_list_1, sorted_list_2)): if item[0] != item[1]: print(i) assert sorted_list_1 == sorted_list_2