Skip to content

Commit fa97fe5

Browse files
authored
Add files via upload
1 parent 6b2dc15 commit fa97fe5

File tree

100 files changed

+4938
-0
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

100 files changed

+4938
-0
lines changed

Abstract Classes & Methods.py

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
from abc import ABC, abstractmethod
2+
# ABC = Abstract Base Class. Abstract class which has least one abstract method in the class.
3+
# Abstract methods are which doesn't have any definition it only has a declaration.
4+
5+
6+
class Computer(ABC): # abstract class Computer which have abstract method process
7+
@abstractmethod
8+
def process(self):
9+
pass
10+
11+
12+
class Laptop(Computer): # cls Laptop is inheriting abstract cls Computer, so it is compulsory to define abstract method
13+
def process(self):
14+
print('its running')
15+
16+
17+
#com = Computer()
18+
#com.process()
19+
com1 = Laptop()
20+
com1.process()

Algorithms/Binary Search.py

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
# Iterative Binary Search Function.
2+
# It returns index of x in given array arr if present, else returns -1
3+
"""
4+
def search(arr, key):
5+
low = 0
6+
high = len(arr) - 1
7+
mid = 0
8+
while low <= high:
9+
mid = (low + high) // 2
10+
if arr[mid] < key: # If x is greater, ignore left half
11+
low = mid + 1
12+
elif arr[mid] > key: # If x is smaller, ignore right half
13+
high = mid - 1
14+
else: # means x is present at mid
15+
return mid
16+
17+
return -1
18+
19+
20+
arr = [1, 2, 3, 6, 9, 10]
21+
key = int(input('Enter the key to Searched: '))
22+
index = search(arr, key)
23+
if index == -1:
24+
print('Key not found')
25+
else:
26+
print('Key found at index', index + 1)
27+
"""
28+
29+
30+
# Recursive binary search.
31+
# Returns index of x in arr if present, else -1
32+
def search(arr, low, high, key):
33+
if low <= high:
34+
mid = (low + high) // 2
35+
if arr[mid] == key: # If element is present at the middle itself
36+
return mid
37+
elif arr[mid] > key: # If element is smaller than mid, then it can only be present in left subarray
38+
return search(arr, low, mid-1, key)
39+
else: # Else the element can only be present in right subarray
40+
return search(arr, mid+1, high, key)
41+
else: # Element is not present in the array
42+
return -1
43+
44+
45+
arr = [1, 2, 3, 6, 9, 10]
46+
key = int(input('Enter the key to Searched: '))
47+
index = search(arr, 0, len(arr)-1, key)
48+
if index == -1:
49+
print('Key not found')
50+
else:
51+
print('Key found at index', index + 1)

Algorithms/Boyer-Moore.py

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
NO_OF_CHARS = 256
2+
3+
4+
# The preprocessing function for Boyer Moore's bad character heuristic
5+
def badCharHeuristic(string, size):
6+
# Initialize all occurrence as -1
7+
badChar = [-1] * NO_OF_CHARS
8+
9+
# Fill the actual value of last occurrence
10+
for i in range(size): # badChar = [-1, -1,...{65, 0},{66, 1}, {67, 2},...-1]
11+
badChar[ord(string[i])] = i
12+
13+
# return initialized list
14+
return badChar
15+
16+
17+
# A pattern searching function that uses Bad Character Heuristic of Boyer Moore Algorithm
18+
def search(txt, pat):
19+
m = len(pat)
20+
n = len(txt)
21+
22+
# create the bad character list by calling the preprocessing function badCharHeuristic() for given pattern
23+
badChar = badCharHeuristic(pat, m)
24+
25+
# s is shift of the pattern with respect to text
26+
s = 0
27+
while s <= n - m:
28+
j = m - 1
29+
30+
# Keep reducing index j of pattern while characters of pattern and text are matching at this shift s
31+
while j >= 0 and pat[j] == txt[s + j]:
32+
j -= 1
33+
34+
# If the pattern is present at current shift, then index j will become -1 after the above loop
35+
if j < 0:
36+
print("Pattern occur at shift = {}".format(s))
37+
# Shift the pattern so that the next character in text aligns with the last occurrence of it in pattern.
38+
# The condition s+m < n is necessary for the case when pattern occurs at the end of text
39+
s += (m - badChar[ord(txt[s + m])] if s + m < n else 1) # badChar[ord(txt[4+3=7]=D)=-1
40+
else:
41+
# Shift the pattern so that the bad character in text aligns with the last occurrence of it in pattern.
42+
# The max function is used to make sure that we get a positive shift.
43+
# We may get a negative shift if the last occurrence of bad character in pattern is on the right side of
44+
# the current character.
45+
s += max(1, j - badChar[ord(txt[s + j])]) # barChar[ ord (txt[0+2]=A) = 65] = 0
46+
47+
48+
# Driver program
49+
if __name__ == '__main__':
50+
txt = "ABAAABCD"
51+
pat = "ABC"
52+
search(txt, pat)

Algorithms/Bubble Sort.py

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
def sort(arr):
2+
for i in range(len(arr) - 1): # Traverse through all array elements, len - 1 because outer loop will repeat one
3+
# time more than needed
4+
swapped = False
5+
for j in range(0, len(arr) - i - 1): # Last i elements are already in place
6+
if arr[j] > arr[j + 1]: # Swap the element, if right is founded smaller than the left element
7+
arr[j], arr[j + 1] = arr[j + 1], arr[j]
8+
swapped = True
9+
if not swapped: # not swapped=not False=True, so if True it will break the i loop if no swap is done in j loop.
10+
break # Time = O(n) for already sorted array.
11+
12+
return arr
13+
14+
15+
arr = [15, 20, 35, 49, 5, 36, 77]
16+
sort(arr)
17+
print(arr)

Algorithms/Insertion Sort.py

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# To sort an array of size N in ascending order:
2+
# Iterate from arr[1] to arr[N] over the array.
3+
# Compare the current element (key) index i to its predecessor index j = i-1.
4+
# If the key element is smaller than its predecessor, compare it to the elements before j= i-2.
5+
# Store the first value(assuming it is the smallest) in temp and move the greater elements one position ahead.
6+
7+
def sort(elements):
8+
for i in range(len(elements)): # at i=0 nothing will work, so lets take i=2 and j=1
9+
small = elements[i]
10+
j = i - 1
11+
while j >= 0 and elements[j] > small: # j index greater than -1 and index j=1 element > index i=2 element
12+
elements[j + 1] = elements[j] # storing j(1) value at j+1 = i = 2
13+
j = j - 1 # j=0 now, so on the next iteration the while loop will check if j=0 > i or not, if it is then
14+
# the swapping continues i.e. storing j value at j+1 = 1 until while one of conditions fails
15+
elements[j + 1] = small # while loop exists at j=-1, so at index 0 storing the smallest element
16+
17+
18+
if __name__ == '__main__':
19+
elements = [99, 77, 66, 88, 33, 22, 11, 0]
20+
sort(elements)
21+
print(elements)
22+

Algorithms/Linear Search.py

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
def search(arr, key):
2+
for i in range(len(arr)):
3+
if arr[i] == key:
4+
return i
5+
return -1
6+
7+
8+
arr = [15, 20, 35, 49, 5, 36, 77]
9+
key = int(input('Enter the key to Searched: '))
10+
index = search(arr, key)
11+
if index == -1:
12+
print('Key not found')
13+
else:
14+
print('Key found at index', index+1)
15+

Algorithms/Merge Sort.py

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
def merge_sort(arr):
2+
if len(arr) <= 1: # when there is one or fewer elements
3+
return
4+
5+
mid = len(arr) // 2
6+
left = arr[:mid] # 0 to mid-1
7+
right = arr[mid:] # mid to len(arr)
8+
9+
# Finding the mid of the passed array. The mid will lead to the creation of 2 separate array lists sending the first
10+
# and second half separately of the array to get divided again and again till reaches 1 element in returning time we
11+
# will start comparing the elements and sorting them. First 2-2 lists of elements then 4-4 lists of elements & so on
12+
# Calling time we divide till 1 Returning time we compare(sort) and merge.
13+
14+
merge_sort(left)
15+
merge_sort(right)
16+
17+
merge_two_sorted_lists(left, right, arr)
18+
19+
20+
def merge_two_sorted_lists(a, b, arr):
21+
len_a = len(a)
22+
len_b = len(b)
23+
24+
i = j = k = 0 # i,j,k are index pointers. i points to array a, j to array b, and k to array arr
25+
26+
while i < len_a and j < len_b: # stopping when reached either end of the lists
27+
if a[i] <= b[j]: # array a value is less, than add it to the array arr and increment a++ index pointers
28+
arr[k] = a[i]
29+
i += 1
30+
else:
31+
arr[k] = b[j]
32+
j += 1
33+
k += 1 # of the two conditions one will be true, & in each array arr pointer k will be incremented++
34+
35+
while i < len_a: # when either one of the lists ended, we copy the remaining elements of(either a or b) in arr
36+
arr[k] = a[i]
37+
i += 1
38+
k += 1
39+
40+
while j < len_b:
41+
arr[k] = b[j]
42+
j += 1
43+
k += 1
44+
45+
46+
if __name__ == '__main__':
47+
elements = [11, 9, 29, 7, 2, 15, 28]
48+
merge_sort(elements)
49+
print(elements)

Algorithms/Quick Sort.py

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
# Algorithm:
2+
# Select pivot, low, and high elements.
3+
# Keep moving low & high pointers until we found the indexes which satisfies the conditions:
4+
# A[low] > A[pivot] and A[high] <= A[pivot]
5+
# If low < high then swap A[low] with A[high] and
6+
# If low >= high then swap A[pivot] with A[high]
7+
8+
def swap(a, b, arr):
9+
if a != b:
10+
arr[a], arr[b] = arr[b], arr[a]
11+
12+
13+
# Hoare partition
14+
def partition(elements, start, end):
15+
pivot_index = start # taking the first index(0) as a pivot in Hoare's partition
16+
pivot = elements[pivot_index] # pivot index value
17+
while start < end: # these while loops will stop at the index which satisfies the conditions
18+
while start < len(elements) and elements[start] <= pivot: # start < size and start value <= pivot value
19+
start += 1 # incrementing start index pointer, i.e. start points to index 2 now, if it pointed to 1 before
20+
21+
while elements[end] > pivot: # it will stop when pivot value > then end value, so we have found the index
22+
end -= 1 # decrementing end index pointer, i.e. end points to index 5 now, if it pointed to 6 before
23+
24+
if start < end:
25+
swap(start, end, elements)
26+
27+
swap(pivot_index, end, elements) # when end >= start, swapping end with pivot, the pivot value at end index will be
28+
return end # sorted element, which is at its perfect index
29+
30+
31+
def partitions(elements, start, end):
32+
pivot = elements[end]
33+
pi = start
34+
for i in range(start, end):
35+
if elements[i] <= pivot:
36+
swap(i, pi, elements)
37+
pi += 1
38+
swap(pi, end, elements)
39+
return pi
40+
41+
42+
def quick_sort(elements, start, end):
43+
if start < end:
44+
pi = partition(elements, start, end) # after finding the middle element we store that at pi index in the Array
45+
quick_sort(elements, start, pi - 1) # in the 0 to pi-1 array & pi +1 to end array, we will again find
46+
quick_sort(elements, pi + 1, end) # partition index(pi) and divide these arrays further till one element
47+
# remains which is implicitly sorted
48+
49+
50+
if __name__ == '__main__':
51+
elements = [11, 9, 29, 7, 2, 15, 28]
52+
quick_sort(elements, 0, len(elements) - 1)
53+
print(elements)

Algorithms/Rabin-Karp.py

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
d = 10 # Let d be the number of characters in the input set
2+
3+
4+
def search(pattern, text, q):
5+
m = len(pattern)
6+
n = len(text)
7+
p = 0
8+
t = 0
9+
h = 1
10+
i = 0
11+
j = 0
12+
13+
for i in range(m-1): # i=0,1
14+
h = (h*d) % q # i=0 h=1*10%13=10, i=1 h=10*10%13=9
15+
16+
# Calculate hash value for pattern and text
17+
for i in range(m): # i=0,1,2
18+
p = (d*p + ord(pattern[i])) % q # i=0 p=10*0+67%13=2 t=10*0+65%13=0, i=1 p=10*2+68%13=10 t=10*0+66%13=1,
19+
t = (d*t + ord(text[i])) % q # i=2 p=10*10+68%13=12 t=10*1+67%13=12
20+
21+
# Find the match
22+
for i in range(n-m+1): # i=0,1,2,3,4,5,6,7
23+
if p == t:
24+
for j in range(m): # j=0,1,2 now comparing text and pattern character by character
25+
if text[i+j] != pattern[j]: # if even one of them dosent match
26+
break
27+
28+
j += 1 # when all charcaters matched perfectly j will be 2, means we have a match
29+
if j == m: # after adding 1 to j, if j matches m means we have found patter at position i+1 and index i
30+
print("Pattern is found at position: " + str(i+1))
31+
32+
if i < n-m: # when current index is less than last position 8(index=7) to be checked
33+
t = (d * (t - ord(text[i]) * h) + ord(text[i+m])) % q # sliding window adding a new char and removing the first char
34+
# 10 * (12 - ord(i=0(A)) * 9) + ord(i+m=3(C)) % 13 = (10 ( 12 - 65 * 9) + 67) % 13 = 5
35+
if t < 0: # if we get t in minus add the prime number to it
36+
t = t+q
37+
38+
39+
text = "ABCCDDAEFG"
40+
pattern = "CDD"
41+
q = 13
42+
search(pattern, text, q)

Algorithms/Selection Sort.py

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order)
2+
# from unsorted part and putting it at the beginning. The algorithm maintains two sub-arrays in a given array.
3+
# 1) The subarray which is already sorted.
4+
# 2) Remaining subarray which is unsorted.
5+
# In every iteration of selection sort, the minimum element (considering ascending order) from the
6+
# unsorted subarray is picked and moved to the sorted subarray.
7+
8+
def sort(arr):
9+
for i in range(len(arr)): # after one phase is completed element present at i=0 will be a sorted element
10+
# then i moves to the next index(i++) now only unsorted elements remains, i=0 will be excluded from now on
11+
min_index = i # Find the minimum element in remaining unsorted array
12+
for j in range(i + 1, len(arr)): # j=i+1 to j=len
13+
if arr[min_index] > arr[j]: # means if i=0 is greater than j=1
14+
min_index = j # then min will store value j index(1) value
15+
arr[i], arr[min_index] = arr[min_index], arr[i] # i=0, j=1 swapped by i=1 and j=0
16+
17+
return arr
18+
19+
20+
arr = [99, 77, 66, 88, 33, 22, 11, 0]
21+
sort(arr)
22+
print(arr)

Algorithms/Shell Sort.py

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
def sort(arr):
2+
size = len(arr) # let size = 10 then the gap we go from 5, 2(floor value), 1
3+
gap = size // 2 # at gap of 1 this algorithm will work same as Insertion sort
4+
5+
while gap > 0:
6+
for i in range(gap, size): # when gap=5, picking elements in array by the gap number for current i, i.e. i=0,5
7+
anchor = arr[i] # at i=0 the while loop will not start till i(5)=j i.e. gap=5 and j should be 5 or greater
8+
j = i # when i=5, anchor[5] = 9 will be compared with index(0) = 11
9+
while j >= gap and arr[j - gap] > anchor: # when j(5)>=5 & arr[5-5=0](11) > anchor(9), swap
10+
arr[j] = arr[j - gap] # arr[5] = arr[0](11)
11+
j -= gap # j=0 and while exists
12+
arr[j] = anchor # at arr[0]= anchor(9)
13+
gap = gap // 2 # now gap will be 2, so i=0,2,4,6,8 will be compared, starting with anchor(2)=7 and j=2
14+
# first 0,2 will be compared then 0,2,6 then 0,2,6,8, @ gap=1 every element will be compared like Insertion sort
15+
16+
17+
if __name__ == '__main__':
18+
arr = [11, 13, 7, 12, 16, 9, 24, 5, 10, 3]
19+
sort(arr)
20+
print(arr)

Algorithms/Swap.py

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Using temporary location
2+
a = 1
3+
b = 2
4+
temp = a
5+
a = b
6+
b = temp
7+
print(a, " ", b)
8+
9+
# Using XOR
10+
a = 3 # 0011
11+
b = 4 # 0100
12+
a = a ^ b
13+
b = a ^ b
14+
a = a ^ b
15+
print(a, " ", b)
16+
17+
# Using Python's rotation of two function
18+
a = 5
19+
b = 6
20+
a, b = b, a
21+
print(a, " ", b)

0 commit comments

Comments
 (0)