Code
Code
2 """
3 Created on Sun Feb 13 14:09:53 2022
4
5 @author: fahad
6 """
7
8 import matplotlib.pyplot as plt
9 import numpy as np
10 from scipy.optimize import curve_fit
11 from scipy.stats import linregress
12 import timeit
13
14
15 class Node:
16 def __init__(self, data, next_node=None):
17 self.data = data
18 self.pointer = next_node
19
20
21 class LinkedList:
22 def __init__(self, datas):
23 self.head = Node(datas[0])
24 n = self.head
25 for i in range(1, len(datas)):
26 g = Node(datas[i])
27 n.pointer = g
28 n = g
29
30 def __str__(self): # Magic function for printing the Linked List
31 s = ''
32 n = self.head
33 while n.pointer is not None:
34 s += f"{n.data}, "
35 n = n.pointer
36 s += str(n.data)
37 return s
38
39 def __len__(self): # Magic function for length of the Linked List
40 l = 0
41 n = self.head
42 while n.pointer is not None:
43 l += 1
44 n = n.pointer
45 return l+1
46
47 def __getitem__(self, index): # Magic function for indexing in the Linked List
48 n = self.head
49 for i in range(index):
50 n = n.pointer
51 return n.data
52
53 def __setitem__(self, index, value): # Magic function for changing a value at an
index in the Linked List
54 n = self.head
55 for i in range(index):
56 n = n.pointer
57 n.data = value
58
59 def search(self, number): # Search function for searching an element in the Linked
List
60 i = 0
61 n = self.head
62 while n.pointer is not None:
63 if number == n.data:
64 print(f"{number} is at index {i}")
65 return
66 n = n.pointer
67 i += 1
68 if n.data == number:
69 print(f"{number} is at index {i}")
70 return
71 print('Not Found')
72
73
74 def mySort(A):
75 for j in range(1, len(A)):
76 key = A[j]
77 i = j - 1
78 while (i > -1 and A[i] > key):
79 A[i+1] = A[i]
80 i = i - 1
81 A[i+1] = key
82
83 ##### Q1 #####
84
85 h = LinkedList([14, 12, 16, 10, 15, 15, 8, 13, 4, 9, 12, 10, 15, 5]) # Initializing an
instance of the LinkedList
86 h[1] = 1 # Changing the value at 1st index
87 print("The value of index 4 is", h[4]) # Printing the value at index 4
88 print("Length of the Linked list is", len(h)) # Printing length of the Linked List
89 print("Linked List:", h) # Printing the whole Linked List
90 h.search(9) # Searching 9 in the Linked List
91 mySort(h) # Sorting the Linked List
92 print(h) # Printing the sorted Linked List
93
94 worstcases = [] # Worstcase lists for mySort
95 lengths = [] # Lengths of worstcase lists
96 linked_times = [] # List of the Linked List times
97 array_times = [] # List of normal array times
98
99 for i in range(1, 15):
100 l = [x for x in range(1, (i*4)+1)]
101 worstcases.append(l[::-1]) # Reversing the list
102 lengths.append(len(l))
103
104 ##### Q2 #####
105
106 def get_linkedlist_time(arr): # Function for getting time of Linked Lists
107 setup = """
108 from __main__ import Node, LinkedList, mySort
109 lst = {}
110 linked_list = LinkedList(lst)""".format(str(arr))
111
112 stmt = "mySort(linked_list)"
113
114 times = timeit.repeat(stmt=stmt, setup=setup, number=10000, repeat=4)
115
116 return min(times)
117
118 def linkedlist_time(n, a, b, c):
119 return (a*(n**3)) + (b*(n**2)) + (c*n)
120
121 for i in worstcases:
122 linked_times.append(get_linkedlist_time(i))
123
124 linkedlist_values, temp = curve_fit(linkedlist_time, lengths, linked_times) # Curve fit
will give the value of a, b and c and store it in linkedlist_values
125
126 slope, intercept, linked_r_value, p_value, std_err = linregress(lengths, linked_times)
# r value for Linked Lists
127
128 ##### Q3 #####
129
130 def get_normal_array_time(arr): # Function for getting time of normal arrays
131 setup = """
132 from __main__ import mySort
133 lst = {}""".format(str(arr))
134
135 stmt = "mySort(lst)"
136
137 times = timeit.repeat(stmt=stmt, setup=setup, number=10000, repeat=4)
138
139 return min(times)
140
141 def normal_array_time(n, a, b):
142 return a*n*n + b*n
143
144 for i in worstcases:
145 array_times.append(get_normal_array_time(i))
146
147 normal_array_values, temp = curve_fit(normal_array_time, lengths, array_times) # Curve
fit will give the value of a and b and store it in normal_array_values
148
149 slope, intercept, normal_r_value, p_value, std_err = linregress(lengths, array_times) #
r value for normal array
150
151 lengths_array = np.array(lengths)
152 lengths_array = np.linspace(lengths_array.min(), lengths_array.max(), 100)
153
154 # Plotting the Graphs
155
156 plt.scatter(lengths, linked_times, color="blue")
157 plt.plot(lengths_array, linkedlist_time(lengths_array, linkedlist_values[0],
linkedlist_values[1], linkedlist_values[2]), label=f"r value for Linked List is
{round(linked_r_value, 4)}", color='red')
158 plt.scatter(lengths, array_times, color="blue")
159 plt.plot(lengths_array, normal_array_time(lengths_array, normal_array_values[0],
normal_array_values[1]), color="green", label=f"r value for normal array is
{round(normal_r_value, 4)}")
160 plt.legend()
161 plt.grid()
162 plt.show()
163