Skip to content

Commit 7a60457

Browse files
Add files via upload
python Experiments
1 parent b832ffd commit 7a60457

6 files changed

+222
-0
lines changed

heap sort.py

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import random
2+
from timeit import default_timer as timer
3+
import matplotlib.pyplot as plt
4+
def heapify(arr, n, i):
5+
largest = i
6+
l = 2 * i + 1
7+
r = 2 * i + 2
8+
if l < n and arr[i] < arr[l]:
9+
largest = l
10+
if r < n and arr[largest] < arr[r]:
11+
largest = r
12+
if largest != i:
13+
arr[i], arr[largest] = arr[largest], arr[i]
14+
heapify(arr, n, largest)
15+
def heapSort(arr):
16+
n = len(arr)
17+
for i in range(n // 2, -1, -1):
18+
heapify(arr, n, i)
19+
for i in range(n - 1, 0, -1):
20+
arr[i], arr[0] = arr[0], arr[i]
21+
heapify(arr, i, 0)
22+
x=[]
23+
y=[]
24+
for i in range(3):
25+
n=int(input("\nEnter the value of n:"))
26+
x.append(n)
27+
arr = [random.randint(0, 10) for _ in range(n)]
28+
print("Array elements before sorting are",arr)
29+
start_time = timer()
30+
ind=heapSort(arr)
31+
end_time = timer()
32+
elapsed_time = end_time - start_time
33+
y.append(elapsed_time)
34+
print("Array elements after sorting are ",arr)
35+
print("Time taken=", elapsed_time)
36+
plt.plot(x,y)
37+
plt.title('Time Taken for heap sort')
38+
plt.xlabel('n')
39+
plt.ylabel('Time (seconds)')
40+
plt.show()

insertion sort.py

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import random
2+
from timeit import default_timer as timer
3+
import matplotlib.pyplot as plt
4+
def insertionSort(array):
5+
for step in range(1, len(array)):
6+
key = array[step]
7+
j = step - 1
8+
while j >= 0 and key < array[j]:
9+
array[j + 1] = array[j]
10+
j = j - 1
11+
array[j + 1] = key
12+
x=[]
13+
y=[]
14+
for i in range(5):
15+
n=int(input("\nenter the value of n:"))
16+
x.append(n)
17+
arr = [random.randint(0, 1000) for _ in range(n)]
18+
print("\nthe array elements are",arr)
19+
start_time = timer()
20+
ind=insertionSort(arr)
21+
end_time = timer()
22+
print("array elements are ", arr)
23+
elapsed_time = end_time - start_time
24+
y.append(elapsed_time)
25+
print("time taken=", elapsed_time)
26+
plt.plot(x,y)
27+
plt.title('Time Taken for insertion sort')
28+
plt.xlabel('n')
29+
plt.ylabel('Time (seconds)')
30+
plt.show()

kth smallest number.py

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import random
2+
def kthSmallest(arr, l, r, k):
3+
if (k > 0 and k <= r - l + 1):
4+
pos = randomPartition(arr, l, r)
5+
if (pos - l == k - 1):
6+
return arr[pos]
7+
if (pos - l > k - 1):
8+
return kthSmallest(arr, l, pos - 1, k)
9+
return kthSmallest(arr, pos + 1, r,k - pos + l - 1)
10+
return 999999999999
11+
def swap(arr, a, b):
12+
temp = arr[a]
13+
arr[a] = arr[b]
14+
arr[b] = temp
15+
def partition(arr, l, r):
16+
x = arr[r]
17+
i = l
18+
for j in range(l, r):
19+
if (arr[j] <= x):
20+
swap(arr, i, j)
21+
i += 1
22+
swap(arr, i, r)
23+
return i
24+
def randomPartition(arr, l, r):
25+
n = r - l + 1
26+
pivot = int(random.random() * n)
27+
swap(arr, l + pivot, r)
28+
return partition(arr, l, r)
29+
if __name__ == '__main__':
30+
arr = [12, 3, 5, 7, 4, 19, 26]
31+
n = len(arr)
32+
k = 3
33+
print("K'th smallest element is",kthSmallest(arr, 0, n - 1, k))

nqueen challenge.py

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
global N
2+
N = 4
3+
def printSolution(board):
4+
for i in range(N):
5+
for j in range(N):
6+
print (board[i][j],end=' ')
7+
print()
8+
def isSafe(board, row, col):
9+
for i in range(col):
10+
if board[row][i] == 1:
11+
return False
12+
for i, j in zip(range(row, -1, -1), range(col, -1, -1)):
13+
if board[i][j] == 1:
14+
return False
15+
for i, j in zip(range(row, N, 1), range(col, -1, -1)):
16+
if board[i][j] == 1:
17+
return False
18+
return True
19+
def solveNQUtil(board, col):
20+
if col >= N:
21+
return True
22+
for i in range(N):
23+
if isSafe(board, i, col):
24+
board[i][col] = 1
25+
if solveNQUtil(board, col + 1) == True:
26+
return True
27+
board[i][col] = 0
28+
return False
29+
def solveNQ():
30+
board = [[0, 0, 0, 0],
31+
[0, 0, 0, 0],
32+
[0, 0, 0, 0],
33+
[0, 0, 0, 0]
34+
]
35+
if solveNQUtil(board, 0) == False:
36+
print ("Solution does not exist")
37+
return False
38+
printSolution(board)
39+
return True
40+
solveNQ()

quick sort.py

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import random
2+
from timeit import default_timer as timer
3+
import matplotlib.pyplot as plt
4+
def partition(array, low, high):
5+
pivot = array[high]
6+
i = low - 1
7+
for j in range(low, high):
8+
if array[j] <= pivot:
9+
i = i + 1
10+
(array[i], array[j]) = (array[j], array[i])
11+
(array[i + 1], array[high]) = (array[high], array[i + 1])
12+
return i + 1
13+
def quickSort(array, low, high):
14+
if low < high:
15+
pi = partition(array, low, high)
16+
quickSort(array, low, pi - 1)
17+
quickSort(array, pi + 1, high)
18+
x=[]
19+
y=[]
20+
for i in range(3):
21+
n=int(input("\nenter the value of n:"))
22+
x.append(n)
23+
arr = [random.randint(0, 1000) for _ in range(n)]
24+
print("\nthe array elements are",arr)
25+
start_time = timer()
26+
ind=quickSort(arr,low=0,high=n-1)
27+
end_time = timer()
28+
print("array elements are ", arr)
29+
elapsed_time = end_time - start_time
30+
y.append(elapsed_time)
31+
print("time taken=", elapsed_time)
32+
plt.plot(x,y)
33+
plt.title('Time Taken for quick sort')
34+
plt.xlabel('n')
35+
plt.ylabel('Time (seconds)')
36+
plt.show()

traveling salesman.py

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import numpy as np
2+
3+
4+
def nearest_neighbor(matrix):
5+
n = matrix.shape[0]
6+
current_city = np.random.randint(n)
7+
visited_cities = [current_city]
8+
total_distance = 0
9+
while len(visited_cities) < n:
10+
nearest_city = np.argmin([matrix[current_city][i] for i in range(n) if i not in visited_cities])
11+
visited_cities.append(nearest_city)
12+
total_distance += matrix[current_city][nearest_city]
13+
current_city = nearest_city
14+
total_distance += matrix[visited_cities[-1]][visited_cities[0]]
15+
visited_cities.append(visited_cities[0])
16+
return visited_cities, total_distance
17+
18+
19+
def calculate_distance_matrix(points):
20+
n = len(points)
21+
dist_matrix = np.zeros((n, n))
22+
for i in range(n):
23+
for j in range(n):
24+
dist_matrix[i][j] = np.sqrt((points[i][0] - points[j][0]) ** 2 + (points[i][1] - points[j][1]) ** 2)
25+
return dist_matrix
26+
points = [(0, 0), (1, 2), (3, 1), (2, 3)]
27+
matrix = calculate_distance_matrix(points)
28+
route, approx_distance = nearest_neighbor(matrix)
29+
from itertools import permutations
30+
perm = permutations(range(len(points)))
31+
optimal_distance = float('inf')
32+
for p in perm:
33+
distance = 0
34+
for i in range(len(p) - 1):
35+
distance += matrix[p[i]][p[i + 1]]
36+
distance += matrix[p[-1]][p[0]]
37+
if distance < optimal_distance:
38+
optimal_distance = distance
39+
print("Points:", points)
40+
print("Approximation Route:", route)
41+
print("Approximation Distance:", approx_distance)
42+
print("Optimal Distance:", optimal_distance)
43+
print("Error Approximation:", (approx_distance - optimal_distance) / optimal_distance)

0 commit comments

Comments
 (0)