Post

Day 19 of 100 Days of Python

Practising DSA

First Program:

1
2
3
4
5
6
7
8
9
underlying_array_size = 10;
user_keys = ["alpha", "beta", "gamma", "delta"];

for key in user_keys:
    s=0
    for i in key:
        s = s+ ord(i)
    ti = s%underlying_array_size
    print(f"Key '{key}' maps to array index: {ti}")

Output:

1
2
3
4
Key 'alpha' maps to array index: 8
Key 'beta' maps to array index: 2
Key 'gamma' maps to array index: 5
Key 'delta' maps to array index: 2

The second program today was to practise Bubble Sort for DSA.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# Bubble Sort

def bubble_sort(arr):
    l = len(arr)
    for i in range(0,l):
        for j in range(0, l-i-1):
            if arr[j]>arr[j+1]:
                arr[j],arr[j+1] = arr[j+1], arr[j]
    return arr

arr = []

print("Enter the number of values ")
n = int(input())
print("Enter values of arrays ")

for i in range(0, n):
    i = int(input())
    arr.append(i)

print("Sorting is asccending order using Bubble Sort")
print(bubble_sort(arr))


Output:

1
2
3
4
5
6
7
8
9
10
Enter the number of values
5
Enter values of arrays
12
45
98
2
178
Sorting is asccending order using Bubble Sort
[2, 12, 45, 98, 178]

The next program was Selection Sort.

1
2
3
4
5
6
7
8
9
10
11
12
#election sort
def selection_sort(arr):
    n = len(arr)
    for i in range(0,n):
        min_idx = i
        for j in range(i+1,n):
            if arr[j]<arr[min_idx]:
                arr[j], arr[min_idx] = arr[min_idx], arr[j]
    return arr

numbers = [29, 10, 14, 37, 13]
print(selection_sort(numbers))

Output:

1
[10, 13, 14, 29, 37]
This post is licensed under CC BY 4.0 by the author.

Trending Tags