├── Notes ├── README.md ├── Stacks.md ├── Recursion.md ├── Circular Arrays.md ├── Linked List.md └── Arrays.md ├── Practice Sheets ├── CSE220 Midterm Practice Sheet.pdf ├── CSE220 Practice Sheet 01 - Arrays.pdf ├── CSE220 Practice Sheet 03 - Linked List.pdf ├── CSE220 Practice Sheet 02 - Circular Arrays.pdf ├── CSE220 Practice Sheet 00 - Array _ Circular Arrays.pdf └── CSE220 Practice Sheet 04 - Doubly Linked List _ Stack.pdf ├── Exam Questions └── CSE220 Quiz 01 _ 02 ( Fall 2022 ).pdf ├── Lab Assignment Questions ├── Spring 2022 │ ├── CSE220 Lab 1 - Arrays.pdf │ ├── CSE220 Lab 5 - Recursion.pdf │ ├── CSE220 Lab 2 - Linked List.pdf │ ├── CSE220 Lab 8 - Trees and Graph.pdf │ ├── CSE220 Lab 3 - Doubly Linked List.pdf │ ├── CSE220 Lab 6 - Searching and Sorting.pdf │ ├── CSE220 Lab 4 - Stack (Parenthesis Balancing).pdf │ └── CSE220 Lab 7 - Key Index Searching _ Sorting, Hashing.pdf └── Fall 2022 │ ├── CSE220 Lab 01 - Arrays (Fall 2022).pdf │ ├── CSE220 Lab 03 - Linked List (Fall 2022).pdf │ ├── CSE220 Lab 06 - Recursion (Fall 2022).pdf │ ├── CSE220 Lab 02 - Circular Arrays (Fall 2022).pdf │ ├── CSE220 Lab 04 - Doubly Linked List (Fall 2022).pdf │ ├── CSE220 Lab 05 - Stack & Parenthesis Balancing (Fall 2022).pdf │ └── CSE220 Lab 07 - Key Indexed Searching & Sorting and Hashing (Fall 2022).pdf ├── Lab Assignment Solutions ├── Spring 2022 │ ├── Assignment 08 │ │ └── Lab 08.pdf │ ├── Assignment 05 │ │ ├── Problem 03.py │ │ ├── Problem 05.py │ │ ├── Problem 04.py │ │ ├── Problem 01.py │ │ └── Problem 02.py │ ├── Assignment 02 │ │ ├── Problem 01.py │ │ ├── Problem 03.py │ │ └── Problem 02.py │ ├── Assignment 01 │ │ ├── Problem 03.py │ │ ├── Problem 01.py │ │ ├── Problem 02.py │ │ ├── Problem 06.py │ │ ├── Problem 09.py │ │ ├── Problem 07.py │ │ ├── Problem 04.py │ │ ├── Problem 11.py │ │ ├── Problem 05.py │ │ ├── Problem 08.py │ │ ├── Problem 10.py │ │ └── CSE220 Lab Assignment 01.ipynb │ ├── Assignment 06 │ │ ├── Problem 07.py │ │ ├── Problem 02.py │ │ ├── Problem 01.py │ │ ├── Problem 06.py │ │ ├── Problem 05.py │ │ ├── Problem 03.py │ │ └── Problem 04.py │ ├── Assignment 07 │ │ ├── Problem 01.py │ │ └── Problem 02.py │ └── Assignment 03 │ │ └── Problem -01.py └── Fall 2022 │ ├── Assignment 06 │ ├── Lab06_21101048.txt │ └── Recursion.py │ ├── Assignment 07 │ ├── Searching -Sorting-Hashing.py │ └── Lab07_21101048.txt │ ├── Assignment 04 │ └── DoublyLinkedList.py │ ├── Assignment 02 │ └── Lab02_21101048.txt │ └── Assignment 03 │ ├── Lab03_21101048.txt │ └── LinkedList2.py ├── README.md └── .gitignore /Notes/README.md: -------------------------------------------------------------------------------- 1 | # Notes 2 | -------------------------------------------------------------------------------- /Notes/Stacks.md: -------------------------------------------------------------------------------- 1 | # Stacks 2 | -------------------------------------------------------------------------------- /Notes/Recursion.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # Recursion 4 | -------------------------------------------------------------------------------- /Practice Sheets/CSE220 Midterm Practice Sheet.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mahrjose/BRACU-CSE220/HEAD/Practice Sheets/CSE220 Midterm Practice Sheet.pdf -------------------------------------------------------------------------------- /Exam Questions/CSE220 Quiz 01 _ 02 ( Fall 2022 ).pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mahrjose/BRACU-CSE220/HEAD/Exam Questions/CSE220 Quiz 01 _ 02 ( Fall 2022 ).pdf -------------------------------------------------------------------------------- /Practice Sheets/CSE220 Practice Sheet 01 - Arrays.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mahrjose/BRACU-CSE220/HEAD/Practice Sheets/CSE220 Practice Sheet 01 - Arrays.pdf -------------------------------------------------------------------------------- /Practice Sheets/CSE220 Practice Sheet 03 - Linked List.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mahrjose/BRACU-CSE220/HEAD/Practice Sheets/CSE220 Practice Sheet 03 - Linked List.pdf -------------------------------------------------------------------------------- /Lab Assignment Questions/Spring 2022/CSE220 Lab 1 - Arrays.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mahrjose/BRACU-CSE220/HEAD/Lab Assignment Questions/Spring 2022/CSE220 Lab 1 - Arrays.pdf -------------------------------------------------------------------------------- /Lab Assignment Solutions/Spring 2022/Assignment 08/Lab 08.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mahrjose/BRACU-CSE220/HEAD/Lab Assignment Solutions/Spring 2022/Assignment 08/Lab 08.pdf -------------------------------------------------------------------------------- /Practice Sheets/CSE220 Practice Sheet 02 - Circular Arrays.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mahrjose/BRACU-CSE220/HEAD/Practice Sheets/CSE220 Practice Sheet 02 - Circular Arrays.pdf -------------------------------------------------------------------------------- /Lab Assignment Questions/Spring 2022/CSE220 Lab 5 - Recursion.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mahrjose/BRACU-CSE220/HEAD/Lab Assignment Questions/Spring 2022/CSE220 Lab 5 - Recursion.pdf -------------------------------------------------------------------------------- /Lab Assignment Questions/Spring 2022/CSE220 Lab 2 - Linked List.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mahrjose/BRACU-CSE220/HEAD/Lab Assignment Questions/Spring 2022/CSE220 Lab 2 - Linked List.pdf -------------------------------------------------------------------------------- /Practice Sheets/CSE220 Practice Sheet 00 - Array _ Circular Arrays.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mahrjose/BRACU-CSE220/HEAD/Practice Sheets/CSE220 Practice Sheet 00 - Array _ Circular Arrays.pdf -------------------------------------------------------------------------------- /Lab Assignment Questions/Fall 2022/CSE220 Lab 01 - Arrays (Fall 2022).pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mahrjose/BRACU-CSE220/HEAD/Lab Assignment Questions/Fall 2022/CSE220 Lab 01 - Arrays (Fall 2022).pdf -------------------------------------------------------------------------------- /Lab Assignment Questions/Spring 2022/CSE220 Lab 8 - Trees and Graph.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mahrjose/BRACU-CSE220/HEAD/Lab Assignment Questions/Spring 2022/CSE220 Lab 8 - Trees and Graph.pdf -------------------------------------------------------------------------------- /Practice Sheets/CSE220 Practice Sheet 04 - Doubly Linked List _ Stack.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mahrjose/BRACU-CSE220/HEAD/Practice Sheets/CSE220 Practice Sheet 04 - Doubly Linked List _ Stack.pdf -------------------------------------------------------------------------------- /Lab Assignment Questions/Spring 2022/CSE220 Lab 3 - Doubly Linked List.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mahrjose/BRACU-CSE220/HEAD/Lab Assignment Questions/Spring 2022/CSE220 Lab 3 - Doubly Linked List.pdf -------------------------------------------------------------------------------- /Lab Assignment Questions/Fall 2022/CSE220 Lab 03 - Linked List (Fall 2022).pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mahrjose/BRACU-CSE220/HEAD/Lab Assignment Questions/Fall 2022/CSE220 Lab 03 - Linked List (Fall 2022).pdf -------------------------------------------------------------------------------- /Lab Assignment Questions/Fall 2022/CSE220 Lab 06 - Recursion (Fall 2022).pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mahrjose/BRACU-CSE220/HEAD/Lab Assignment Questions/Fall 2022/CSE220 Lab 06 - Recursion (Fall 2022).pdf -------------------------------------------------------------------------------- /Lab Assignment Questions/Spring 2022/CSE220 Lab 6 - Searching and Sorting.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mahrjose/BRACU-CSE220/HEAD/Lab Assignment Questions/Spring 2022/CSE220 Lab 6 - Searching and Sorting.pdf -------------------------------------------------------------------------------- /Lab Assignment Questions/Fall 2022/CSE220 Lab 02 - Circular Arrays (Fall 2022).pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mahrjose/BRACU-CSE220/HEAD/Lab Assignment Questions/Fall 2022/CSE220 Lab 02 - Circular Arrays (Fall 2022).pdf -------------------------------------------------------------------------------- /Lab Assignment Questions/Fall 2022/CSE220 Lab 04 - Doubly Linked List (Fall 2022).pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mahrjose/BRACU-CSE220/HEAD/Lab Assignment Questions/Fall 2022/CSE220 Lab 04 - Doubly Linked List (Fall 2022).pdf -------------------------------------------------------------------------------- /Lab Assignment Questions/Spring 2022/CSE220 Lab 4 - Stack (Parenthesis Balancing).pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mahrjose/BRACU-CSE220/HEAD/Lab Assignment Questions/Spring 2022/CSE220 Lab 4 - Stack (Parenthesis Balancing).pdf -------------------------------------------------------------------------------- /Lab Assignment Questions/Spring 2022/CSE220 Lab 7 - Key Index Searching _ Sorting, Hashing.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mahrjose/BRACU-CSE220/HEAD/Lab Assignment Questions/Spring 2022/CSE220 Lab 7 - Key Index Searching _ Sorting, Hashing.pdf -------------------------------------------------------------------------------- /Lab Assignment Questions/Fall 2022/CSE220 Lab 05 - Stack & Parenthesis Balancing (Fall 2022).pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mahrjose/BRACU-CSE220/HEAD/Lab Assignment Questions/Fall 2022/CSE220 Lab 05 - Stack & Parenthesis Balancing (Fall 2022).pdf -------------------------------------------------------------------------------- /Lab Assignment Questions/Fall 2022/CSE220 Lab 07 - Key Indexed Searching & Sorting and Hashing (Fall 2022).pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mahrjose/BRACU-CSE220/HEAD/Lab Assignment Questions/Fall 2022/CSE220 Lab 07 - Key Indexed Searching & Sorting and Hashing (Fall 2022).pdf -------------------------------------------------------------------------------- /Lab Assignment Solutions/Spring 2022/Assignment 05/Problem 03.py: -------------------------------------------------------------------------------- 1 | # Problem -03 2 | 3 | 4 | def hocBuilder(height): 5 | if height == 0: 6 | return f"0 \nUse common sense! We cannot build house with 0 height!!!" 7 | 8 | if height == 1: 9 | return 8 10 | 11 | return 5 + hocBuilder(height - 1) 12 | 13 | 14 | print("\nNo. 3-->") 15 | height = int(input("(HocBuilder) Enter Height: ")) 16 | print(hocBuilder(height)) 17 | -------------------------------------------------------------------------------- /Lab Assignment Solutions/Spring 2022/Assignment 02/Problem 01.py: -------------------------------------------------------------------------------- 1 | # Problem 01 2 | 3 | 4 | class Node: 5 | def __init__(self, data=None): 6 | self.data = data 7 | self.next = None 8 | 9 | 10 | class LinkedList: 11 | def __init__(self): 12 | self.head = None 13 | 14 | 15 | def main(): 16 | MyList = LinkedList() 17 | elem1 = Node(3) 18 | MyList.head = elem1 19 | 20 | 21 | if __name__ == "__main__": 22 | main() 23 | -------------------------------------------------------------------------------- /Lab Assignment Solutions/Spring 2022/Assignment 01/Problem 03.py: -------------------------------------------------------------------------------- 1 | # Problem -03 2 | 3 | 4 | def remove(arr, size, index): 5 | 6 | if index < 0 or index > size: 7 | print("Invalid Index") 8 | return 9 | 10 | for i in range(size): 11 | if i >= index and i <= size - 1: 12 | arr[i] = arr[i + 1] 13 | 14 | arr[size - 1] = 0 15 | 16 | print(arr) 17 | 18 | 19 | def main(): 20 | source = [10, 20, 30, 40, 50, 0, 0] 21 | remove(source, 5, 2) 22 | 23 | 24 | if __name__ == "__main__": 25 | main() 26 | -------------------------------------------------------------------------------- /Lab Assignment Solutions/Spring 2022/Assignment 06/Problem 07.py: -------------------------------------------------------------------------------- 1 | # Problem -07 2 | 3 | arr = [None] * 1000 4 | 5 | 6 | def fibonacci(num): 7 | if num == 0 or num == 1: 8 | return num 9 | else: 10 | if arr[num] == None: 11 | arr[num] = fibonacci(num - 1) + fibonacci(num - 2) 12 | 13 | return arr[num] 14 | 15 | 16 | print("\nNo. 7 - Recursive Fibonacci Algorithm with memoization --> ") 17 | n = int(input("Input n to find nth fibonacci number -> ")) 18 | print(f"{n}th fibonacci number is -> ", end="") 19 | print(fibonacci(n)) 20 | print("\n") 21 | -------------------------------------------------------------------------------- /Lab Assignment Solutions/Spring 2022/Assignment 01/Problem 01.py: -------------------------------------------------------------------------------- 1 | # Probem -01 2 | 3 | 4 | def shiftLeft(arr, k): 5 | 6 | for i in range(len(arr)): 7 | if i < len(arr) - k and k > 0: 8 | arr[i] = arr[i + k] 9 | 10 | else: 11 | if k <= 0: 12 | print("Invalid 'k' Position") 13 | return 14 | 15 | else: 16 | arr[i] = 0 17 | 18 | print(arr) 19 | 20 | 21 | def main(): 22 | source = [10, 20, 30, 40, 50, 60] 23 | shiftLeft(source, 3) 24 | 25 | 26 | if __name__ == "__main__": 27 | main() 28 | -------------------------------------------------------------------------------- /Lab Assignment Solutions/Spring 2022/Assignment 01/Problem 02.py: -------------------------------------------------------------------------------- 1 | # Problem -02 2 | 3 | 4 | def rotateLeft(arr, k): 5 | 6 | temp = [value for value in arr[:k]] 7 | 8 | for i in range(len(arr)): 9 | if i < len(arr) - k and k > 0: 10 | arr[i] = arr[i + k] 11 | 12 | else: 13 | if k <= 0 or k > len(arr): 14 | print("Invalid 'k' position") 15 | return 16 | else: 17 | arr[i] = temp[i - (len(arr) - k)] 18 | 19 | print(arr) 20 | 21 | 22 | def main(): 23 | source = [10, 20, 30, 40, 50, 60] 24 | rotateLeft(source, 3) 25 | 26 | 27 | if __name__ == "__main__": 28 | main() 29 | -------------------------------------------------------------------------------- /Lab Assignment Solutions/Spring 2022/Assignment 01/Problem 06.py: -------------------------------------------------------------------------------- 1 | # Problem -06 2 | 3 | 4 | def array_series(num) -> list: 5 | 6 | arr = [0] * (num * num) 7 | 8 | i = 1 9 | while i <= num: 10 | j = 1 11 | while j <= i: 12 | arr[(i * num) - j] = j 13 | 14 | j += 1 15 | i += 1 16 | 17 | return arr 18 | 19 | 20 | def main(): 21 | 22 | # Uncomment for manual input 23 | # print(array_series(int(input("Input 'n' = ")))) 24 | 25 | print(f"n = 2: {array_series(2)}") 26 | print(f"n = 3: {array_series(3)}") 27 | print(f"n = 4: {array_series(4)}") 28 | 29 | 30 | if __name__ == "__main__": 31 | main() 32 | -------------------------------------------------------------------------------- /Lab Assignment Solutions/Spring 2022/Assignment 06/Problem 02.py: -------------------------------------------------------------------------------- 1 | # Problem -02 2 | 3 | 4 | def rec_insertion_sort(array, index): 5 | if index <= 1: 6 | return 7 | 8 | rec_insertion_sort(array, index - 1) 9 | 10 | i = index - 2 11 | j = array[index - 1] 12 | 13 | while array[i] > j and i >= 0: 14 | array[i + 1] = array[i] 15 | i -= 1 16 | 17 | array[i + 1] = j 18 | 19 | 20 | print("\nNo. 2 - Sorting with Insertion Recursion Sort --> \n") 21 | print("Unsorted -> ", end="") 22 | array = [6, 7, 8, 9, 4, 3, 20, 0, 0] 23 | print(array) 24 | index = len(array) 25 | rec_insertion_sort(array, index) 26 | print("Sorted -> ", end="") 27 | print(array) 28 | print("\n") 29 | -------------------------------------------------------------------------------- /Lab Assignment Solutions/Spring 2022/Assignment 05/Problem 05.py: -------------------------------------------------------------------------------- 1 | # Problem -05 2 | 3 | 4 | class FinalQ: 5 | def print(self, array, idx): 6 | if idx < len(array): 7 | profit = self.calcProfit(array[idx]) 8 | print(f"{idx+1}. Investment: {array[idx]}; Profit: {profit}") 9 | self.print(array, idx + 1) 10 | 11 | def calcProfit(self, investment): 12 | if investment <= 25000: 13 | return 0.0 14 | 15 | elif investment <= 100000: 16 | return 45 + self.calcProfit(investment - 1000) 17 | 18 | elif investment > 100000: 19 | return 80 + self.calcProfit(investment - 1000) 20 | 21 | else: 22 | return 0 23 | 24 | 25 | print("\nNo. 5-->") 26 | array = [25000, 100000, 250000, 350000] 27 | f = FinalQ() 28 | f.print(array, 0) 29 | -------------------------------------------------------------------------------- /Lab Assignment Solutions/Spring 2022/Assignment 01/Problem 09.py: -------------------------------------------------------------------------------- 1 | # Circular arr 2 | # Problem -01 3 | 4 | 5 | def palindrome(arr, start, size) -> bool: 6 | new_arr = [] 7 | 8 | for _ in range(size): 9 | if arr[start] != 0: 10 | new_arr.append(arr[start]) 11 | start += 1 12 | if start == len(arr): 13 | start = 0 14 | 15 | arr_half = (len(new_arr) + 1) // 2 16 | 17 | if new_arr[0:arr_half] == new_arr[-1 : -(arr_half + 1) : -1]: 18 | return True 19 | else: 20 | return False 21 | 22 | 23 | def main(): 24 | source = [20, 10, 0, 0, 0, 10, 20, 30] 25 | print(palindrome(source, start=5, size=5)) 26 | 27 | source = [10, 20, 0, 0, 0, 10, 20, 30] 28 | print(palindrome(source, start=5, size=5)) 29 | 30 | 31 | if __name__ == "__main__": 32 | main() 33 | -------------------------------------------------------------------------------- /Lab Assignment Solutions/Spring 2022/Assignment 01/Problem 07.py: -------------------------------------------------------------------------------- 1 | # Problem -07 2 | 3 | 4 | def maxBunch(arr) -> None: 5 | 6 | streak, currnt_streak = 1, 1 7 | for i in range(len(arr)): 8 | # if this is the last element, print the result 9 | if i == len(arr) - 1: 10 | print(streak) 11 | return 12 | 13 | elif arr[i] == arr[i + 1]: 14 | currnt_streak += 1 15 | else: 16 | currnt_streak = 1 17 | 18 | # if current streak is higher than previous streaks 19 | # make this the new current streak 20 | if currnt_streak >= streak: 21 | streak = currnt_streak 22 | 23 | 24 | def main(): 25 | source = [1, 2, 2, 3, 4, 4, 4] 26 | maxBunch(source) 27 | 28 | source = [1, 1, 2, 2, 1, 1, 1, 1] 29 | maxBunch(source) 30 | 31 | 32 | if __name__ == "__main__": 33 | main() 34 | -------------------------------------------------------------------------------- /Lab Assignment Solutions/Spring 2022/Assignment 06/Problem 01.py: -------------------------------------------------------------------------------- 1 | # Problem -01 2 | 3 | 4 | def findMin(arr, start, end): 5 | if start == end: 6 | return start 7 | 8 | min = findMin(arr, start + 1, end) 9 | if arr[start] > arr[min]: 10 | return min 11 | 12 | return start 13 | 14 | 15 | def rec_selection_sort(arr, start, end): 16 | if start < end: 17 | min = findMin(arr, start + 1, end) 18 | if arr[start] > arr[min]: 19 | temp = arr[start] 20 | arr[start] = arr[min] 21 | arr[min] = temp 22 | 23 | rec_selection_sort(arr, start + 1, end) 24 | 25 | 26 | print("\nNo. 1 - Sorting with Selection Recursion Sort -> \n") 27 | print("Unsorted -> ", end="") 28 | arr = [100, 3, 5, 1, 55, 88, 6, 4, 7, 88, 2, 1, 0] 29 | print(arr) 30 | rec_selection_sort(arr, 0, len(arr) - 1) 31 | print("Sorted -> ", end="") 32 | print(arr) 33 | print("\n") 34 | -------------------------------------------------------------------------------- /Lab Assignment Solutions/Spring 2022/Assignment 01/Problem 04.py: -------------------------------------------------------------------------------- 1 | # Problem -04 2 | 3 | 4 | def removeAll(arr, size, element): 5 | if size <= 0 and size > len(arr): 6 | print("Invalid Size") 7 | return 8 | 9 | # If index item is equal to the element to remove 10 | # replace that index item as 0 11 | for i in range(size): 12 | if arr[i] == element: 13 | arr[i] = 0 14 | 15 | j = 0 16 | for i in range(size): 17 | # If index item is not 0 (after converting 18 | # all target elements to 0) 19 | # Make the array compact with the non zero items 20 | if arr[i] != 0: 21 | temp = arr[j] 22 | arr[j] = arr[i] 23 | arr[i] = temp 24 | j += 1 25 | 26 | print(arr) 27 | 28 | 29 | def main(): 30 | source = [10, 2, 30, 2, 50, 2, 2, 0, 0] 31 | removeAll(source, 7, 2) 32 | 33 | 34 | if __name__ == "__main__": 35 | main() 36 | -------------------------------------------------------------------------------- /Lab Assignment Solutions/Spring 2022/Assignment 01/Problem 11.py: -------------------------------------------------------------------------------- 1 | # Problem -03 2 | 3 | import random 4 | 5 | 6 | def musical_chair(players): 7 | player_num = len(players) 8 | 9 | while player_num > 1: 10 | 11 | print(f"Current Players: {players}") 12 | var = random.randint(0, 3) 13 | 14 | if var == 1: 15 | position = int(player_num / 2) 16 | print( 17 | f"\nThe music stopped!!!\nPlayer Name: {players[position]} in Position: {position} is out of the Game!\n" 18 | ) 19 | players.pop(position) 20 | 21 | # Circulate items 22 | players.insert(0, players[len(players) - 1]) 23 | players.pop(len(players) - 1) 24 | player_num = len(players) 25 | print(f"We've got the Winner!!!\nAaand the winner is: {players[0]}") 26 | 27 | 28 | def main(): 29 | players = ["Guts", "Eren", "Kaneki", "Araragi", "Hachiman", "Itachi", "Lelouch"] 30 | musical_chair(players) 31 | 32 | 33 | if __name__ == "__main__": 34 | main() 35 | -------------------------------------------------------------------------------- /Lab Assignment Solutions/Spring 2022/Assignment 06/Problem 06.py: -------------------------------------------------------------------------------- 1 | # Problem -06 2 | 3 | 4 | def rec_binary_search(array, left, right, value): 5 | if left <= right: 6 | 7 | mid_value = int((left + right) // 2) 8 | 9 | if array[mid_value] == value: 10 | return mid_value 11 | 12 | elif array[mid_value] < value: 13 | return rec_binary_search(array, mid_value + 1, right, value) 14 | 15 | else: 16 | return rec_binary_search(array, left, mid_value - 1, value) 17 | 18 | else: 19 | return -1 20 | 21 | 22 | print("\nNo. 6 - Recursive Binary Search ->\n") 23 | array = [1, 2, 3, 4, 5, 6, 7, 20, 30, 55, 200] 24 | print(f"Array - {array}") 25 | value = int(input("Item to Search? -> ")) 26 | result = rec_binary_search(array, 0, len(array) - 1, value) 27 | if result != -1: 28 | print( 29 | f"\nThe searched element : {value}, is present in the array at index {result}." 30 | ) 31 | else: 32 | print("\nElement is not present in array.") 33 | 34 | print("\n") 35 | -------------------------------------------------------------------------------- /Lab Assignment Solutions/Spring 2022/Assignment 01/Problem 05.py: -------------------------------------------------------------------------------- 1 | # Problem -05 2 | 3 | 4 | def Splitting_array(arr): 5 | arr_A = [0] 6 | arr_B = [] 7 | flag = None 8 | 9 | for i in range(len(arr)): 10 | if i == 0: 11 | arr_A[i] = arr[i] 12 | arr_B = arr[i + 1 : (len(arr))] 13 | if sum(arr_A) == sum(arr_B): 14 | flag = True 15 | break 16 | else: 17 | arr_A = [] 18 | flag = False 19 | else: 20 | arr_A = arr[0 : i + 1] 21 | arr_B = arr[i + 1 : (len(arr))] 22 | if sum(arr_A) == sum(arr_B): 23 | flag = True 24 | break 25 | else: 26 | flag = False 27 | print(flag) 28 | 29 | 30 | def main(): 31 | arr = [1, 1, 1, 2, 1] 32 | Splitting_array(arr) 33 | 34 | arr = [2, 1, 1, 2, 1] 35 | Splitting_array(arr) 36 | 37 | arr = [10, 3, 1, 2, 10] 38 | Splitting_array(arr) 39 | 40 | 41 | if __name__ == "__main__": 42 | main() 43 | -------------------------------------------------------------------------------- /Lab Assignment Solutions/Spring 2022/Assignment 01/Problem 08.py: -------------------------------------------------------------------------------- 1 | # Problem -08 2 | 3 | 4 | def repetition(arr) -> bool: 5 | 6 | repeated_values = [] 7 | # Create a dictionary for counting item repetition 8 | dictionary = {item: arr.count(item) for item in arr} 9 | 10 | # if item repetition value is more than 1, 11 | # item has been repeated so add to a list for more experiment 12 | for repeated_count in dictionary.values(): 13 | if repeated_count > 1: 14 | repeated_values.append(repeated_count) 15 | 16 | # if 2 or more value are the same, length of set would be 17 | # smaller than the main list meaing there're same repeated value 18 | # for 2 or more items 19 | if len(repeated_values) == len(set(repeated_values)): 20 | return False 21 | else: 22 | return True 23 | 24 | 25 | def main(): 26 | source = [4, 5, 6, 6, 4, 3, 6, 4] 27 | print(repetition(source)) 28 | 29 | source = [3, 4, 6, 3, 4, 7, 4, 6, 8, 6, 6] 30 | print(repetition(source)) 31 | 32 | 33 | if __name__ == "__main__": 34 | main() 35 | -------------------------------------------------------------------------------- /Lab Assignment Solutions/Spring 2022/Assignment 05/Problem 04.py: -------------------------------------------------------------------------------- 1 | # Problem -04 2 | 3 | # 4(a) 4 | def numPattern(num): 5 | if num == 0: 6 | return 7 | 8 | numPattern(num - 1) 9 | print(num, end=" ") 10 | 11 | 12 | def patternPrint(num): 13 | if num == 0: 14 | return 15 | 16 | patternPrint(num - 1) 17 | numPattern(num) 18 | print() 19 | 20 | 21 | print("\nNo. 4(a)-->") 22 | num = int(input("Pattern Input: ")) 23 | patternPrint(num) 24 | 25 | 26 | # 4(b) 27 | def spacePattern(num): 28 | if num == 0: 29 | return 30 | 31 | spacePattern(num - 1) 32 | print(" ", end=" ") 33 | 34 | 35 | def numPattern(num): 36 | if num == 0: 37 | return 38 | 39 | numPattern(num - 1) 40 | print(num, end=" ") 41 | 42 | 43 | def patternPrint(num, var): 44 | if num == 0: 45 | return 46 | 47 | spacePattern(num - 1) 48 | numPattern(var - num + 1) 49 | print() 50 | patternPrint(num - 1, var) 51 | 52 | 53 | print("\nNo. 4(b)-->") 54 | num = int(input("Reverse Pattern Input: ")) 55 | patternPrint(num, num) 56 | -------------------------------------------------------------------------------- /Lab Assignment Solutions/Spring 2022/Assignment 05/Problem 01.py: -------------------------------------------------------------------------------- 1 | # Problem -01 2 | 3 | # 1(a) 4 | def factorial(n): 5 | if n == 1 or n == 0: 6 | return 1 7 | 8 | return n * factorial(n - 1) 9 | 10 | 11 | print("\nNo. 1(a)-->") 12 | n = int(input("To find n!, Please input n -> ")) 13 | print(f"{n}! is = ", end="") 14 | print(factorial(n)) 15 | 16 | # 1(b) 17 | def fibonacci(num): 18 | if num == 0: 19 | return 0 20 | 21 | if num == 1 or num == 2: 22 | return 1 23 | 24 | if num > 2: 25 | return fibonacci(num - 1) + fibonacci(num - 2) 26 | 27 | 28 | print("\nNo. 1(b)-->") 29 | n = int(input("Input n to find nth fibonacci number -> ")) 30 | print(f"{n}th fibonacci number is -> ", end="") 31 | print(fibonacci(n)) 32 | 33 | # 1(c) 34 | def printArray(arr, index=0): 35 | if index == len(arr): 36 | return 37 | 38 | print(arr[index]) 39 | printArray(arr, index + 1) 40 | 41 | 42 | print("\nNo. 1(c)-->") 43 | printArray([1, 2, 3, 4, 5]) 44 | 45 | # 1(d) 46 | def powerN(base, n): 47 | if n == 0: 48 | return 1 49 | 50 | return base * powerN(base, n - 1) 51 | 52 | 53 | print("\nNo. 1(d)-->") 54 | print(powerN(3, 1)) 55 | print(powerN(3, 2)) 56 | print(powerN(3, 3)) 57 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # CSE220: Data Sturctures (Spring - 2022 & Fall 2022) 2 | 3 | > Solutions for the BRAC University Computer Science and Engineering Course - CSE220 Lab Assignments (Spring - 2022). 4 | 5 | > 6 | > All the solutions are written with [Python 3.9 ](https://www.python.org/downloads/) 7 | 8 | # Course Outline: 9 | 10 | ## **Lecture 1:** Linear Array 11 | 12 | ## **Lecture 2:** Linear Array Manipulation Examples 13 | * cse220 Lab Assignment 01 14 | 15 | ## **Lecture 3:** Circular Array 16 | 17 | ## **Lecture 4:** Linked List 18 | 19 | ## **Lecture 5:** Linked List Manipulation 20 | * cse220 Lab Assignment 02 21 | 22 | ## **Lecture 6:** Linked List Types & DHDLCL 23 | * cse220 Lab Assignment 03 24 | 25 | ## **Lecture 7:** Stack 26 | * cse220 Lab Assignment 04 27 | 28 | ## **Lecture 8:** Queue 29 | 30 | ## **Lecture 9:** Recursion - Basics 31 | * cse220 Lab Assignment 05 32 | 33 | ## **Lecture 10:** Memoization 34 | 35 | ## **Lecture 11:** Sorting & Searching 36 | * cse220 Lab Assignment 06 37 | 38 | ## **Lecture 12:** Key Index Search & Sort 39 | 40 | ## **Lecture 13:** Hashtable 41 | * cse220 Lab Assignment 07 42 | 43 | ## **Lecture 14:** Tree data Structure: Basic 44 | 45 | ## **Lecture 15:** Tree data Structure : Representation 46 | 47 | ## **Lecture 16:** Binary Search Tree (BST) 48 | 49 | ## **Lecture 17:** Graph: Basic 50 | 51 | ## **Lecture 18:** Graph: Representation & Traversal 52 | * cse220 Lab Assignment 08 53 | 54 | -------------------------------------------------------------------------------- /Lab Assignment Solutions/Spring 2022/Assignment 05/Problem 02.py: -------------------------------------------------------------------------------- 1 | # Problem -02 2 | 3 | # 2(a) 4 | def decimalToBinary(num): 5 | if num == 0: 6 | return 0 7 | 8 | return decimalToBinary(num // 2) * 10 + (num % 2) 9 | 10 | 11 | print("\nNo. 2(a)-->") 12 | n = int(input("Input Decimal to find the binary -> ")) 13 | print(f"{n} in Binary is -> ", end="") 14 | print(decimalToBinary(n)) 15 | 16 | 17 | # 2(b) 18 | class Node: 19 | def __init__(self, element=None): 20 | self.element = element 21 | self.next = None 22 | 23 | 24 | class LinkedList: 25 | def __init__(self): 26 | self.head = None 27 | 28 | def append(self, element): 29 | node = Node(element) 30 | current = self.head 31 | 32 | if self.head is None: 33 | self.head = node 34 | node = self.head 35 | 36 | else: 37 | while current.next is not None: 38 | current = current.next 39 | 40 | current.next = node 41 | 42 | def printList(self): 43 | 44 | current = self.head 45 | while current is not None: 46 | print(f"({current.element} - {current.next})") 47 | current = current.next 48 | 49 | 50 | MyList = LinkedList() 51 | MyList.append(10) 52 | MyList.append(20) 53 | MyList.append(30) 54 | MyList.append(40) 55 | 56 | 57 | def linkedListAdd(head): 58 | if head == None: 59 | return 0 60 | 61 | return head.element + linkedListAdd(head.next) 62 | 63 | 64 | print("\nNo. 2(b)-->") 65 | print(linkedListAdd(MyList.head)) 66 | 67 | # 2(c) 68 | def printReverse(head): 69 | if head == None: 70 | return 71 | 72 | printReverse(head.next) 73 | print(head.element) 74 | 75 | 76 | print("\nNo. 2(c)-->") 77 | printReverse(MyList.head) 78 | -------------------------------------------------------------------------------- /Lab Assignment Solutions/Spring 2022/Assignment 06/Problem 05.py: -------------------------------------------------------------------------------- 1 | # Problem -05 2 | 3 | 4 | class Node: 5 | def __init__(self, value, next, prev): 6 | self.value = value 7 | self.next = next 8 | self.prev = prev 9 | 10 | 11 | class Doublylinkedlist: 12 | def __init__(self, array): 13 | self.head = Node(array[0], None, None) 14 | tail = self.head 15 | for i in range(1, len(array)): 16 | new_node = Node(array[i], None, tail) 17 | tail.next = new_node 18 | tail = new_node 19 | 20 | def showList(self): 21 | if self.head.next is None: 22 | print("Empty list") 23 | else: 24 | head = self.head 25 | while self.head is not None: 26 | if head.next is None: 27 | print(head.value) 28 | break 29 | else: 30 | print(head.value, end=" <-> ") 31 | head = head.next 32 | 33 | def insertion_sort(self): 34 | head = self.head 35 | if head == None: 36 | return 37 | else: 38 | while head is not None: 39 | tail = head.next 40 | while tail and tail.prev is not None and tail.value < tail.prev.value: 41 | temp = tail.value 42 | tail.value = tail.prev.value 43 | tail.prev.value = temp 44 | 45 | tail = tail.prev 46 | 47 | head = head.next 48 | 49 | 50 | print("\nNo. 5 - Sorting Doubly LinkedList with Insertion Sort -->\n") 51 | array = [4, 7, 45, 9, 33, 2, 8] 52 | doublylinkedlist = Doublylinkedlist(array) 53 | print("Unsorted LinkedList ===> ", end="") 54 | doublylinkedlist.showList() 55 | doublylinkedlist.insertion_sort() 56 | print("Sorted LinkedList ===> ", end="") 57 | doublylinkedlist.showList() 58 | print("\n") 59 | -------------------------------------------------------------------------------- /Lab Assignment Solutions/Spring 2022/Assignment 01/Problem 10.py: -------------------------------------------------------------------------------- 1 | # Problem -02 2 | 3 | 4 | def intersection(array_1, start_1, size_1, array_2, start_2, size_2): 5 | 6 | intersection_array = [] 7 | 8 | # Array 1 9 | array_1_A = [] 10 | array_1_B = [] 11 | for i in range(1, len(array_1)): 12 | if array_1[i] == 0 and array_1[i - 1] != 0: 13 | for j in range(i): 14 | array_1_B.append(array_1[j]) 15 | 16 | for i in range(1, len(array_1)): 17 | if array_1[i] != 0 and array_1[i - 1] == 0: 18 | for j in range(i, len(array_1)): 19 | array_1_A.append(array_1[j]) 20 | 21 | # Array 2 22 | array_2_A = [] 23 | array_2_B = [] 24 | for i in range(1, len(array_2)): 25 | if array_2[i] == 0 and array_2[i - 1] != 0: 26 | for j in range(i): 27 | array_2_B.append(array_2[j]) 28 | 29 | for i in range(1, len(array_2)): 30 | if array_2[i] != 0 and array_2[i - 1] == 0: 31 | for j in range(i, len(array_2)): 32 | array_2_A.append(array_2[j]) 33 | 34 | # Combine 35 | new_array_1 = array_1_A + array_1_B 36 | new_array_2 = array_2_A + array_2_B 37 | 38 | # search for common items 39 | for i in range(len(new_array_1)): 40 | new = new_array_1[i] 41 | for i in range(len(new_array_2)): 42 | if new == new_array_2[i]: 43 | if new not in intersection_array: 44 | intersection_array.append(new) 45 | else: 46 | continue 47 | else: 48 | continue 49 | 50 | print(intersection_array) 51 | 52 | 53 | def main(): 54 | array_1 = [40, 50, 0, 0, 0, 10, 20, 30] 55 | array_2 = [10, 20, 5, 0, 0, 0, 0, 0, 5, 40, 15, 25] 56 | 57 | intersection(array_1, 5, 5, array_2, 8, 7) 58 | 59 | 60 | if __name__ == "__main__": 61 | main() 62 | -------------------------------------------------------------------------------- /Lab Assignment Solutions/Spring 2022/Assignment 07/Problem 01.py: -------------------------------------------------------------------------------- 1 | # Problem -01 2 | 3 | 4 | def maxValue(list): 5 | val = list[0] 6 | for i in list: 7 | if val < abs(i): 8 | val = abs(i) 9 | return val 10 | 11 | 12 | class keyIndex: 13 | def __init__(self, k): 14 | self.k = k 15 | 16 | global max_val 17 | max_val = maxValue(self.k) 18 | self.temp = [0] * ((max_val * 2) + 1) 19 | 20 | for i in self.k: 21 | if 0 == self.temp[max_val + i]: 22 | self.temp[max_val + i] = 1 23 | else: 24 | self.temp[max_val + i] = self.temp[max_val + i] + 1 25 | 26 | def search(self, key): 27 | k = int(key) 28 | if k + max_val < 0 or k + max_val >= len(self.temp): 29 | return False 30 | else: 31 | if self.temp[k + max_val] != 0: 32 | return True 33 | else: 34 | return False 35 | 36 | def sort(self): 37 | indx = 0 38 | for i in range(0, len(self.temp)): 39 | if len(self.k) <= indx: 40 | print(self.k) 41 | break 42 | 43 | if self.temp[i] >= 1: 44 | for _ in range(0, self.temp[i]): 45 | self.k[indx] = i - max_val 46 | indx += 1 47 | 48 | def printlist(self): 49 | print(self.temp) 50 | 51 | 52 | print("No. 1 -->") 53 | list = [-5, 8, 4, 6, 1, -8, -10] 54 | key_indx = keyIndex(list) 55 | key_indx.printlist() 56 | 57 | print("") 58 | try: 59 | var = int(input("Search for : ")) 60 | except ValueError: 61 | var = 3 62 | print("User didnot manually enter the search value. Searching for default value 3.") 63 | 64 | if key_indx.search(var): 65 | print(f"{var} is in the list.") 66 | else: 67 | print(f"{var} is not in the list.") 68 | 69 | print() 70 | print("Sorted List -> ", end="") 71 | key_indx.sort() 72 | -------------------------------------------------------------------------------- /Lab Assignment Solutions/Spring 2022/Assignment 06/Problem 03.py: -------------------------------------------------------------------------------- 1 | # Problem -03 2 | 3 | 4 | class Node: 5 | def __init__(self, value): 6 | self.value = value 7 | self.next = None 8 | 9 | 10 | class LinkedList: 11 | def __init__(self, arr): 12 | self.head = None 13 | tail = None 14 | 15 | for i in arr: 16 | new_node = Node(i) 17 | if self.head == None: 18 | self.head = new_node 19 | tail = new_node 20 | 21 | else: 22 | tail.next = new_node 23 | tail = new_node 24 | 25 | def showList(self): 26 | 27 | current = self.head 28 | 29 | if current is None: 30 | print("Empty List") 31 | else: 32 | while current is not None: 33 | if current.next is None: 34 | print(current.value) 35 | break 36 | else: 37 | print(current.value, end=" -> ") 38 | current = current.next 39 | 40 | def bubble_sort(self): 41 | head = self.head 42 | tail = None 43 | 44 | if self.head is None: 45 | return 46 | 47 | else: 48 | while head != None: 49 | tail = head.next 50 | while tail != None: 51 | 52 | if tail.value < head.value: 53 | temp = head.value 54 | head.value = tail.value 55 | tail.value = temp 56 | 57 | tail = tail.next 58 | 59 | head = head.next 60 | 61 | 62 | print("\nNo. 3 - Sorting Singly LinkedList with Bubble Sort -->\n") 63 | array = [4, 7, 45, 9, 33, 2, 8] 64 | linkedlist = LinkedList(array) 65 | print("Unsorted LinkedList ===> ", end="") 66 | linkedlist.showList() 67 | linkedlist.bubble_sort() 68 | print("Sorted LinkedList ===> ", end="") 69 | linkedlist.showList() 70 | print("\n") 71 | -------------------------------------------------------------------------------- /Lab Assignment Solutions/Spring 2022/Assignment 07/Problem 02.py: -------------------------------------------------------------------------------- 1 | # Problem -02 2 | 3 | 4 | vowels = ["A", "E", "I", "O", "U"] 5 | consonants = [ 6 | "B", 7 | "C", 8 | "D", 9 | "F", 10 | "G", 11 | "H", 12 | "J", 13 | "K", 14 | "L", 15 | "M", 16 | "N", 17 | "P", 18 | "Q", 19 | "R", 20 | "S", 21 | "T", 22 | "V", 23 | "W", 24 | "X", 25 | "Y", 26 | "Z", 27 | ] 28 | 29 | 30 | class Hashstring: 31 | def __init__(self, str): 32 | self.str = str 33 | 34 | def string_get(self): 35 | return self.str 36 | 37 | def string_key(self): 38 | val = 0 39 | var = 0 40 | 41 | for i in self.str: 42 | if i in consonants: 43 | val = val + 1 44 | if i not in consonants and i not in vowels: 45 | var += int(i) 46 | 47 | string_key = (val * 24) + var 48 | return string_key 49 | 50 | 51 | class Hashtable: 52 | def __init__(self, size=9): 53 | self.size = size 54 | self.list = [0] * size 55 | 56 | def function(self, string_key): 57 | return string_key % self.size 58 | 59 | def add(self, s): 60 | val = s.string_key() 61 | position = self.function(val) 62 | for i in range(1, self.size): 63 | if self.list[position] == 0: 64 | self.list[position] = s.string_get() 65 | break 66 | else: 67 | position = (val + i) % self.size 68 | 69 | def print(self): 70 | for i in range(self.size): 71 | print(self.list[i]) 72 | 73 | 74 | hash_table = Hashtable() 75 | list = [ 76 | "ZJO9V49NDOU", 77 | "X9ZAR2JD6F7", 78 | "KD9LNX46TT2", 79 | "G94F5SMC2DG", 80 | "5YLHRBO79CT", 81 | "WN2NY54F22D", 82 | "YVRFKVUOH6Y", 83 | "ST1E89B8A32", 84 | "5W8UWJSDCJH", 85 | ] 86 | 87 | print("No. 2 -->\n") 88 | for i in list: 89 | s = Hashstring(i) 90 | hash_table.add(s) 91 | 92 | hash_table.print() 93 | -------------------------------------------------------------------------------- /Lab Assignment Solutions/Spring 2022/Assignment 06/Problem 04.py: -------------------------------------------------------------------------------- 1 | # Problem -04 2 | 3 | 4 | class Node: 5 | def __init__(self, value): 6 | self.value = value 7 | self.next = None 8 | 9 | 10 | class LinkedList: 11 | def __init__(self, arr): 12 | self.head = None 13 | tail = None 14 | 15 | for i in arr: 16 | new_node = Node(i) 17 | if self.head == None: 18 | self.head = new_node 19 | tail = new_node 20 | 21 | else: 22 | tail.next = new_node 23 | tail = new_node 24 | 25 | def showList(self): 26 | current = self.head 27 | if current is None: 28 | print("Empty List") 29 | else: 30 | while current is not None: 31 | if current.next is None: 32 | print(current.value) 33 | break 34 | else: 35 | print(current.value, end=" -> ") 36 | current = current.next 37 | 38 | def selection_sort(self): 39 | head = self.head 40 | 41 | if self.head is None: 42 | return 43 | else: 44 | while head.next != None: 45 | tail = head 46 | val = head.value 47 | next_val = head.next 48 | 49 | while next_val != None: 50 | if val > next_val.value: 51 | val = next_val.value 52 | tail = next_val 53 | 54 | next_val = next_val.next 55 | 56 | temp = head.value 57 | head.value = tail.value 58 | tail.value = temp 59 | 60 | head = head.next 61 | 62 | 63 | print("\nNo. 4 - Sorting Singly LinkedList with Selection Sort -->\n") 64 | array = [4, 7, 45, 9, 33, 2, 8] 65 | linkedlist = LinkedList(array) 66 | print("Unsorted LinkedList ===> ", end="") 67 | linkedlist.showList() 68 | linkedlist.selection_sort() 69 | print("Sorted LinkedList ===> ", end="") 70 | linkedlist.showList() 71 | print("\n") 72 | -------------------------------------------------------------------------------- /Notes/Circular Arrays.md: -------------------------------------------------------------------------------- 1 | # Circular Arrays 2 | 3 | #### Thumb Rule 1 4 | When traversing a circular Array: 5 | * One variable as Loop Controller (How many times the loop is going to run) 6 | * Different variable for index of Circular Array 7 | 8 | #### Thumb Rule 2 9 | Whenever you increment the index of a circular array, always mod the incremented value with the circular array's length. 10 | 11 | > index + 1 % len(arr) 12 | 13 | #### Thumb Rule 3 14 | 15 | Watch [this video](https://bux.bracu.ac.bd/courses/course-v1:buX+CSE220+2022_Spring/courseware/3ab32391b7054488b5260b23b080f632/be648c7fad1b47f380e4eb3c07664c8a/?activate_block_id=block-v1%3AbuX%2BCSE220%2B2022_Spring%2Btype%40sequential%2Bblock%40be648c7fad1b47f380e4eb3c07664c8a) 16 | 17 | > Last_index = (start + size - 1) % len(arr) 18 | 19 | #### Thumb Rule 4 20 | Whenever you decrement the index of a circular array, always check, keep a check wheater it became negative. If it does, point it to the end of the array. 21 | 22 | #### 23 | 24 | 25 | #### Forward Printing a circular Array 26 | 27 | ```py 28 | def printForward(arr, start, size): 29 | index = start 30 | i = 0 31 | 32 | while (i < size): 33 | print(arr[index]) 34 | index = (index + 1) % len(arr) 35 | i += 1 36 | 37 | circular_arr = [40,50,0,0,0,0,0,0,10,20,30] 38 | printForward(circular_arr, 8, 5) 39 | ``` 40 | Output: 41 | ```txt 42 | 10 43 | 20 44 | 30 45 | 40 46 | 50 47 | ``` 48 | #### Reverse Printing a Circular Array 49 | 50 | ```py 51 | def printReverse(arr,start,size): 52 | index=(start + size - 1) % len(arr) 53 | i = 0 54 | 55 | while(i < size): 56 | print(arr[index]) 57 | index = index - 1 58 | 59 | if(index<0): 60 | index = len(arr) - 1 61 | 62 | i += 1 63 | 64 | 65 | circularArray=[40,50,0,0,0,0,0,0,10,20,30] 66 | printReverse(circularArray,8,5) 67 | ``` 68 | 69 | #### Creating a Circular Array from Linear Arrays 70 | 71 | ```py 72 | def circularize(linear,start,size): 73 | 74 | circular=[0]*len(linear) 75 | 76 | index=start 77 | 78 | i=0 79 | 80 | while(i A linked list is a sequence of data elements, which are connected together via **links**. Each data elements contains a connection to another data element in form of a pointer. 4 | 5 | ![LinkedListExample.png](https://i.imgur.com/9I8jwnW.png) 6 | 7 | Some difference between traditional arrays and linked lists are, 8 | 9 | Advanges / Disadvatages | Arrays | Linked List 10 | |---: | :---|---: | 11 | Random Access | We can Randomly access array values with array indexes. For instance, `arr[35]` would give us the value stored in the 36th index and we don't need to access or touch any other index or values in the array. | We need to touch the previous index or object to goto the next object or index.| 12 | 13 | 14 | ### Linked List - Basic Operations 15 | 16 | 17 | #### List Iteration 18 | 19 | ```py 20 | n = head 21 | while n is not None: 22 | # Do Something 23 | n = n.next 24 | ``` 25 | #### Count function 26 | 27 | Given a list, returns the number of nodes are present in the list. 28 | 29 | ```py 30 | def countNode(head): 31 | count = 0 32 | n = head 33 | while n is not None: 34 | count += 1 35 | n = n.next 36 | 37 | return count 38 | ``` 39 | #### Get function 40 | Given head of the linked list, and an index, returns the value stored into the index of the list. If the index is invalid returns `-1` 41 | 42 | ```py 43 | def get(head, index): 44 | count = 0 45 | n = head 46 | while n is not None: 47 | if count == index: 48 | return n.element 49 | 50 | count += 1 51 | n = n.next 52 | 53 | return -1 54 | ``` 55 | 56 | #### Node At function 57 | 58 | Takes Node Head, list size and index as input and returns the address of the node, that is stored in the index. Returns `None` if the index is invalid. 59 | 60 | ```py 61 | def nodeAt(head, size, index): 62 | if (index < 0 or index >= size): 63 | return None 64 | 65 | n = head 66 | for _ in range(0, index): 67 | n = n.next 68 | 69 | return n 70 | ``` 71 | 72 | #### Set function 73 | 74 | Given an node index, give us the option to change the value stored in that index. (Assuming that the input index is right) 75 | 76 | ```py 77 | def set(head, index, element): 78 | count = 0 79 | n = head 80 | while n is not None: 81 | if count == index: 82 | n.element = element 83 | 84 | count += 1 85 | n = n.next 86 | ``` 87 | 88 | #### Search function 89 | 90 | Given the linked list and an element, if the element can be found in the linked list, returns the position of that element. If the element is not in the list reutrns `-1`. 91 | 92 | ```py 93 | def indexOf(head, element): 94 | index = 0 95 | n = head 96 | while n is not None: 97 | if (n.element == element): 98 | reuturn index 99 | 100 | index += 1 101 | n = n.next 102 | 103 | return -1 104 | ``` 105 | 106 | ### Insert Elements in the list 107 | 108 | #### At the beginning 109 | 110 | ```py 111 | 112 | ``` 113 | 114 | #### At middle 115 | 116 | ```py 117 | 118 | ``` 119 | 120 | #### At the End 121 | 122 | ```py 123 | 124 | ``` 125 | 126 | ```py 127 | 128 | ``` -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Folders 2 | Misc/ 3 | Assignment Submission Files/ 4 | 5 | # VSCode 6 | .vscode/* 7 | !.vscode/settings.json 8 | !.vscode/tasks.json 9 | !.vscode/launch.json 10 | !.vscode/extensions.json 11 | *.code-workspace 12 | 13 | # Local History for Visual Studio Code 14 | .history/ 15 | 16 | # Common credential files 17 | **/credentials.json 18 | **/client_secrets.json 19 | **/client_secret.json 20 | *creds* 21 | *.dat 22 | *password* 23 | *.httr-oauth* 24 | 25 | # Private Node Modules 26 | node_modules/ 27 | creds.js 28 | 29 | # Private Files 30 | *.json 31 | *.csv 32 | *.csv.gz 33 | *.tsv 34 | *.tsv.gz 35 | *.xlsx 36 | 37 | 38 | # Mac/OSX 39 | .DS_Store 40 | 41 | 42 | # Byte-compiled / optimized / DLL files 43 | __pycache__/ 44 | *.py[cod] 45 | *$py.class 46 | 47 | # C/C++ extensions 48 | .cpp-output/* 49 | *.so 50 | 51 | # Distribution / packaging 52 | .Python 53 | build/ 54 | develop-eggs/ 55 | dist/ 56 | downloads/ 57 | eggs/ 58 | .eggs/ 59 | lib/ 60 | lib64/ 61 | parts/ 62 | sdist/ 63 | var/ 64 | wheels/ 65 | share/python-wheels/ 66 | *.egg-info/ 67 | .installed.cfg 68 | *.egg 69 | MANIFEST 70 | 71 | # PyInstaller 72 | # Usually these files are written by a python script from a template 73 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 74 | *.manifest 75 | *.spec 76 | 77 | # Installer logs 78 | pip-log.txt 79 | pip-delete-this-directory.txt 80 | 81 | # Unit test / coverage reports 82 | htmlcov/ 83 | .tox/ 84 | .nox/ 85 | .coverage 86 | .coverage.* 87 | .cache 88 | nosetests.xml 89 | coverage.xml 90 | *.cover 91 | *.py,cover 92 | .hypothesis/ 93 | .pytest_cache/ 94 | cover/ 95 | 96 | # Translations 97 | *.mo 98 | *.pot 99 | 100 | # Django stuff: 101 | *.log 102 | local_settings.py 103 | db.sqlite3 104 | db.sqlite3-journal 105 | 106 | # Flask stuff: 107 | instance/ 108 | .webassets-cache 109 | 110 | # Scrapy stuff: 111 | .scrapy 112 | 113 | # Sphinx documentation 114 | docs/_build/ 115 | 116 | # PyBuilder 117 | .pybuilder/ 118 | target/ 119 | 120 | # Jupyter Notebook 121 | .ipynb_checkpoints 122 | 123 | # IPython 124 | profile_default/ 125 | ipython_config.py 126 | 127 | # pyenv 128 | # For a library or package, you might want to ignore these files since the code is 129 | # intended to run in multiple environments; otherwise, check them in: 130 | # .python-version 131 | 132 | # pipenv 133 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 134 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 135 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 136 | # install all needed dependencies. 137 | #Pipfile.lock 138 | 139 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 140 | __pypackages__/ 141 | 142 | # Celery stuff 143 | celerybeat-schedule 144 | celerybeat.pid 145 | 146 | # SageMath parsed files 147 | *.sage.py 148 | 149 | # Environments 150 | .env 151 | .venv 152 | env/ 153 | venv/ 154 | ENV/ 155 | env.bak/ 156 | venv.bak/ 157 | 158 | # Spyder project settings 159 | .spyderproject 160 | .spyproject 161 | 162 | # Rope project settings 163 | .ropeproject 164 | 165 | # mkdocs documentation 166 | /site 167 | 168 | # mypy 169 | .mypy_cache/ 170 | .dmypy.json 171 | dmypy.json 172 | 173 | # Pyre type checker 174 | .pyre/ 175 | 176 | # pytype static type analyzer 177 | .pytype/ 178 | 179 | # Cython debug symbols 180 | cython_debug/ -------------------------------------------------------------------------------- /Lab Assignment Solutions/Spring 2022/Assignment 03/Problem -01.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self, data, next, prev): 3 | self.data = data 4 | self.next = next 5 | self.prev = prev 6 | 7 | 8 | class Doublylist: 9 | def __init__(self, a): 10 | self.head = Node(a[0], None, None) 11 | tail = self.head 12 | for i in range(1, len(a)): 13 | new_node = Node(a[i], None, tail) 14 | tail.next = new_node 15 | tail = new_node 16 | 17 | def showList(self): 18 | if self.head.next is None: 19 | print("Empty list") 20 | else: 21 | head = self.head 22 | while self.head is not None: 23 | if head.next is None: 24 | print(head.data) 25 | break 26 | else: 27 | print(head.data, "->", end=" ") 28 | head = head.next 29 | 30 | def insert(self, newElement): 31 | head = self.head 32 | new_node = Node(newElement, None, None) 33 | while new_node.next is None: 34 | if head.data == new_node.data: 35 | print("key already exists") 36 | break 37 | if head.next is None: 38 | head.next = new_node 39 | new_node.prev = head 40 | break 41 | head = head.next 42 | 43 | def insert_index(self, newElement, index): 44 | condition = False 45 | if index == 0: 46 | new_node = Node(newElement, self.head, None) 47 | self.head.prev = new_node 48 | self.head = new_node 49 | else: 50 | n = self.head 51 | counter = 0 52 | while n is not None: 53 | n = n.next 54 | if condition is False: 55 | n = self.head 56 | while n is not None: 57 | counter = counter + 1 58 | if n.data == newElement: 59 | condition = True 60 | print("key already exists") 61 | if counter == index: 62 | new_node = Node(newElement, n.next, n.prev) 63 | n.next.prev = new_node 64 | n.prev.next = new_node 65 | n = n.next 66 | 67 | def remove(self, index): 68 | if self.head == None: 69 | print("list is empty") 70 | else: 71 | 72 | counter = 0 73 | head = self.head 74 | while head is not None: 75 | 76 | if index == counter: 77 | head.next.prev = head.prev 78 | head.prev.next = head.next 79 | counter = counter + 1 80 | head = head.next 81 | if index > counter: 82 | print("index out of range") 83 | 84 | def removeKey(self, key): 85 | head = self.head 86 | while head is not None: 87 | if head.data == key: 88 | head.next.prev = head.prev 89 | head.prev.next = head.next 90 | head = head.next 91 | 92 | return key 93 | 94 | 95 | arr = [1, 2, 3, 4, 5] 96 | 97 | mylist = Doublylist(arr) 98 | mylist.showList() 99 | print("Insert 7") 100 | mylist.insert(7) 101 | mylist.showList() 102 | print("Insert 6 at the 5th index") 103 | mylist.insert_index(6, 5) 104 | mylist.showList() 105 | print("Remove 2") 106 | mylist.remove(2) 107 | mylist.showList() 108 | key = mylist.removeKey(3) 109 | print("Removed Key", key) 110 | mylist.showList() 111 | -------------------------------------------------------------------------------- /Lab Assignment Solutions/Spring 2022/Assignment 02/Problem 03.py: -------------------------------------------------------------------------------- 1 | # Problem -03 2 | 3 | 4 | class Node: 5 | def __init__(self, element=None): 6 | self.element = element 7 | self.next = None 8 | 9 | 10 | class LinkedList: 11 | def __init__(self, array) -> None: 12 | self.head = None 13 | 14 | for element in array: 15 | 16 | node = Node(element) 17 | 18 | if self.head == None: 19 | self.head = node 20 | node = self.head 21 | continue 22 | 23 | current = self.head 24 | while current.next is not None: 25 | current = current.next 26 | 27 | current.next = node 28 | 29 | def push(self, element): 30 | 31 | if isinstance(element, Node): 32 | node = element 33 | else: 34 | node: Node = Node(element) 35 | 36 | if self.head is None: 37 | self.head = node 38 | node = self.head 39 | return 40 | 41 | current = self.head 42 | while current.next is not None: 43 | current = current.next 44 | 45 | current.next = node 46 | 47 | def showList(self) -> None: 48 | current = self.head 49 | 50 | if current is not None: 51 | while current is not None: 52 | if current.next is None: 53 | print(current.element) 54 | 55 | else: 56 | print(current.element, end=" -> ") 57 | 58 | current = current.next 59 | else: 60 | print("Empty LinkedList") 61 | 62 | # No. 1 63 | def onlyEven(self): 64 | 65 | evenLinkedList = LinkedList([]) 66 | 67 | current = self.head 68 | while current is not None: 69 | if current.element % 2 == 0: 70 | evenLinkedList.push(current.element) 71 | 72 | current = current.next 73 | 74 | return evenLinkedList.showList() 75 | 76 | def count(self, element): 77 | 78 | counter = 0 79 | 80 | if self.head == None: 81 | return counter 82 | 83 | current = self.head 84 | while current is not None: 85 | if current.element == element: 86 | counter += 1 87 | 88 | current = current.next 89 | 90 | return counter 91 | 92 | # No. 2 93 | def isInList(self, element) -> bool: 94 | if self.count(element) > 0: 95 | return True 96 | else: 97 | return False 98 | 99 | # No. 3 100 | def reverse(self): 101 | prev = None 102 | current = self.head 103 | while current is not None: 104 | next = current.next 105 | current.next = prev 106 | prev = current 107 | current = next 108 | 109 | self.head = prev 110 | 111 | # No. 4 112 | def sort(self): 113 | pass 114 | 115 | # No. 5 116 | def sum(self): 117 | sum = 0 118 | 119 | current = self.head 120 | while current is not None: 121 | sum += current.element 122 | current = current.next 123 | 124 | return sum 125 | 126 | # No. 6 127 | def rotateLeft(self, times=1): 128 | pass 129 | 130 | def rotateRight(self, times=1): 131 | pass 132 | 133 | 134 | MyList = LinkedList([1, 2, 5, 3, 8]) 135 | MyList2 = LinkedList([101, 120, 25, 91, 87, 1]) 136 | ###############--No. 01--############### 137 | print() 138 | print("*No. 1 -->") 139 | print("OnlyEven LinkedList from ===> ", end="") 140 | MyList.showList() 141 | MyList.onlyEven() 142 | print() 143 | print("OnlyEven LinkedList from ===> ", end="") 144 | MyList2.showList() 145 | MyList2.onlyEven() 146 | print("\n") 147 | print() 148 | ###############--No. 02--############### 149 | print("*No. 2 -->") 150 | print("Is 7 in 1 -> 2 -> 5 -> 3 -> 8 ===> ", end="") 151 | print(MyList.isInList(7)) 152 | print() 153 | print("Is 87 in 101 -> 120 -> 25 -> 91-> 87 -> 1 ===> ", end="") 154 | print(MyList2.isInList(87)) 155 | print("\n") 156 | print() 157 | ###############--No. 03--############### 158 | print("*No. 3 -->") 159 | listToRev = LinkedList([1, 2, 5, 3, 8]) 160 | print("Reversing 1 -> 2 -> 5 -> 3 -> 8 ===> ", end="") 161 | listToRev.reverse() 162 | listToRev.showList() 163 | print("\n") 164 | print() 165 | ###############--No. 04--############### 166 | print("*No. 4 -->") 167 | print("\n") 168 | print() 169 | ###############--No. 05--############### 170 | print("*No. 5 -->") 171 | print("Sum of all elements in 1 -> 2 -> 5 -> 3-> 8 ===> ", end="") 172 | print(MyList.sum()) 173 | print("\n") 174 | print() 175 | ###############--No. 06--############### 176 | print("*No. 6 -->") 177 | listToRotate1 = LinkedList([3, 2, 5, 1, 8]) 178 | listToRotate2 = LinkedList([3, 2, 5, 1, 8]) 179 | print("Rotating 3 -> 2 -> 5 -> 1-> 8 Left 2 times ===> ", end="") 180 | listToRotate1.rotateLeft(2) 181 | print() 182 | print("Rotating 3 -> 2 -> 5 -> 1-> 8 Left 2 times ===> ", end="") 183 | listToRotate2.rotateRight(2) 184 | print("\n") 185 | print() 186 | -------------------------------------------------------------------------------- /Lab Assignment Solutions/Fall 2022/Assignment 06/Lab06_21101048.txt: -------------------------------------------------------------------------------- 1 | # ========Lab 05============ 2 | # Name: Mirza Mahrab Hossain Rudra 3 | # Student ID: 21101048 4 | # Section 15 5 | # ========================== 6 | 7 | # =========================== Task 01 ======================= 8 | #========== 1a): Factorial (n!) using recursive algorithm ========= 9 | 10 | def factorial(n): 11 | 12 | if (n==0 or n==1): 13 | return 1 14 | 15 | else: 16 | return n*factorial(n-1) 17 | 18 | print("========No. 1a)========") 19 | print("4! ->", end=" ") 20 | print(factorial(4)) 21 | print() 22 | 23 | #============ 1b): n-th Fibonacci Number============ 24 | 25 | def fib(n): 26 | 27 | if (n < 2): 28 | return n 29 | else: 30 | return fib(n-1)+fib(n-2) 31 | 32 | print("========No. 1b)========") 33 | print("Printing 1st fibonacci term:") 34 | print(fib(1)) 35 | print("Printing 20th fibonacci term:") 36 | print(fib(20)) 37 | print() 38 | 39 | #============== 1c): print elements of array ============= 40 | 41 | def printArray(array, start): 42 | if (start == len(array)): 43 | return 44 | else: 45 | print(array[start], end=" ") 46 | return printArray(array, start + 1) 47 | 48 | print("========No. 1c)========") 49 | print("Given Array: [10, 20, 30, 40]") 50 | printArray([10,20,30,40],0) 51 | print("\n") 52 | 53 | #============ 1d): power(base, n) using recursion ========= 54 | 55 | def powerN(base, n): 56 | if (n == 1): 57 | return base 58 | else: 59 | return base*powerN(base,n-1) 60 | 61 | print("========No. 1d)========") 62 | print("powerN(3,1) -> ", end=" ") 63 | print(powerN(3,1)) 64 | print("powerN(3,2) -> ", end=" ") 65 | print(powerN(3,2)) 66 | print("powerN(3,3) -> ", end=" ") 67 | print(powerN(3,3)) 68 | print() 69 | 70 | # =========================== Task 02 ======================= 71 | # =========2a): Decimal to Binary (divide by 2, returns the mods)======== 72 | 73 | def decToBin(n): 74 | if (n == 0): 75 | print(0,end='') 76 | return 77 | else: 78 | decToBin(n//2) 79 | print(n % 2 , end='') 80 | 81 | # test method decToBin(n) : 82 | print("========No. 2a)========") 83 | print("Decimal to binary: ") 84 | print("3 ->", end=" ") 85 | decToBin(3) 86 | print() 87 | print("11 ->", end=" ") 88 | decToBin(11) 89 | print("\n") 90 | 91 | #================================================================== 92 | 93 | #Node Class 94 | class Node: 95 | def __init__(self, data = None, next = None): 96 | self.data = data 97 | self.next = next 98 | 99 | ll_n4 = Node(40) 100 | ll_n3 = Node(30,ll_n4) 101 | ll_n2 = Node(20,ll_n3) 102 | ll_n1 = Node(10,ll_n2) 103 | 104 | #============ 2b) : Sum of elements of Linked List=============== 105 | 106 | def sum(node): 107 | 108 | if (node.next == None): 109 | return node.data 110 | else: 111 | return node.data + sum(node.next) 112 | 113 | print("========No. 2b)========") 114 | print("Sum of Linked List:") 115 | print("Linked List: 10 -> 20 -> 30 -> 40\nSum:", end=" ") 116 | print(sum(ll_n1)) 117 | print() 118 | 119 | # ========== 2c): print ll elements in reverse order ========== 120 | 121 | def printRev(node): 122 | 123 | if (node.next == None): 124 | print(node.data) 125 | else: 126 | printRev(node.next) 127 | print(node.data) 128 | 129 | print("========No. 2c)========") 130 | print("Recursively Printing Linked List Elems:") 131 | printRev(ll_n1) 132 | print() 133 | 134 | # ======================== Task 03 ============================= 135 | def hocBuilder(height): 136 | if (height < 1): 137 | return 0 138 | elif (height == 1): 139 | return 8 140 | else: 141 | return 5 + hocBuilder(height - 1) 142 | 143 | print("========No. 3)========") 144 | print("hocBuilder(5) ->" , end=" ") 145 | print(hocBuilder(5)) 146 | print() 147 | 148 | # ========================= Task 04 ============================== 149 | # ========= 4a) : pattern printing using recursion ========== 150 | 151 | def printPattern(m): 152 | if (m == 0): 153 | print(" ") 154 | else: 155 | printPattern(m-1) 156 | printSeq(m) 157 | 158 | def printSeq(m): 159 | if (m == 0): 160 | print(" ") 161 | else: 162 | printSeq(m-1) 163 | print(m,end=" ") 164 | 165 | print("========No. 4a)========") 166 | printPattern(5) 167 | print("\n") 168 | 169 | # ======== 4b): Pattern printing ================== 170 | 171 | def pattern(m, n): 172 | 173 | if (m == 0): 174 | return 175 | 176 | printSpace(m - 1) 177 | printSeq2(n - m + 1) 178 | print() 179 | 180 | pattern(m - 1, n) 181 | 182 | def printSpace(m): 183 | 184 | if (m == 0): 185 | return 186 | 187 | print(" ", end=" ") 188 | printSpace(m - 1) 189 | 190 | def printSeq2(m): 191 | 192 | if (m == 0): 193 | return 194 | 195 | printSeq2(m - 1) 196 | print(m, end =" ") 197 | 198 | print("========No. 4a)========") 199 | print() 200 | pattern(5,5) 201 | print() 202 | 203 | # ====================== Task 05 ========================= 204 | class FinalQ: 205 | 206 | def print(self,array,idx): 207 | if(idx 25000 and investment <= 100000): 217 | return 45 + self.calcProfit(investment-1000) 218 | elif (investment > 100000): 219 | return 80 + self.calcProfit(investment-1000) 220 | else: 221 | return 0 222 | 223 | print("========No. 5)========") 224 | array = [25000,100000,250000,350000] 225 | f = FinalQ() 226 | f.print(array,0) 227 | -------------------------------------------------------------------------------- /Lab Assignment Solutions/Fall 2022/Assignment 06/Recursion.py: -------------------------------------------------------------------------------- 1 | # ========Lab 05============ 2 | # Name: Mirza Mahrab Hossain Rudra 3 | # Student ID: 21101048 4 | # Section 15 5 | # ========================== 6 | 7 | # =========================== Task 01 ======================= 8 | #========== 1a): Factorial (n!) using recursive algorithm ========= 9 | 10 | def factorial(n): 11 | 12 | if (n==0 or n==1): 13 | return 1 14 | 15 | else: 16 | return n*factorial(n-1) 17 | 18 | print("========No. 1a)========") 19 | print("4! ->", end=" ") 20 | print(factorial(4)) 21 | print() 22 | 23 | #============ 1b): n-th Fibonacci Number============ 24 | 25 | def fib(n): 26 | 27 | if (n < 2): 28 | return n 29 | else: 30 | return fib(n-1)+fib(n-2) 31 | 32 | print("========No. 1b)========") 33 | print("Printing 1st fibonacci term:") 34 | print(fib(1)) 35 | print("Printing 20th fibonacci term:") 36 | print(fib(20)) 37 | print() 38 | 39 | #============== 1c): print elements of array ============= 40 | 41 | def printArray(array, start): 42 | if (start == len(array)): 43 | return 44 | else: 45 | print(array[start], end=" ") 46 | return printArray(array, start + 1) 47 | 48 | print("========No. 1c)========") 49 | print("Given Array: [10, 20, 30, 40]") 50 | printArray([10,20,30,40],0) 51 | print("\n") 52 | 53 | #============ 1d): power(base, n) using recursion ========= 54 | 55 | def powerN(base, n): 56 | if (n == 1): 57 | return base 58 | else: 59 | return base*powerN(base,n-1) 60 | 61 | print("========No. 1d)========") 62 | print("powerN(3,1) -> ", end=" ") 63 | print(powerN(3,1)) 64 | print("powerN(3,2) -> ", end=" ") 65 | print(powerN(3,2)) 66 | print("powerN(3,3) -> ", end=" ") 67 | print(powerN(3,3)) 68 | print() 69 | 70 | # =========================== Task 02 ======================= 71 | # =========2a): Decimal to Binary (divide by 2, returns the mods)======== 72 | 73 | def decToBin(n): 74 | if (n == 0): 75 | print(0,end='') 76 | return 77 | else: 78 | decToBin(n//2) 79 | print(n % 2 , end='') 80 | 81 | # test method decToBin(n) : 82 | print("========No. 2a)========") 83 | print("Decimal to binary: ") 84 | print("3 ->", end=" ") 85 | decToBin(3) 86 | print() 87 | print("11 ->", end=" ") 88 | decToBin(11) 89 | print("\n") 90 | 91 | #================================================================== 92 | 93 | #Node Class 94 | class Node: 95 | def __init__(self, data = None, next = None): 96 | self.data = data 97 | self.next = next 98 | 99 | ll_n4 = Node(40) 100 | ll_n3 = Node(30, ll_n4) 101 | ll_n2 = Node(20, ll_n3) 102 | ll_n1 = Node(10, ll_n2) 103 | 104 | #============ 02_b : Sum of elements of Linked List=============== 105 | 106 | def sum(node): 107 | 108 | if (node.next == None): 109 | return node.data 110 | else: 111 | return node.data + sum(node.next) 112 | 113 | print("========No. 2b)========") 114 | print("Sum of Linked List:") 115 | print("Linked List: 10 -> 20 -> 30 -> 40\nSum:", end=" ") 116 | print(sum(ll_n1)) 117 | print() 118 | 119 | # ========== 02_c: print ll elements in reverse order ========== 120 | 121 | def printRev(node): 122 | 123 | if (node.next == None): 124 | print(node.data) 125 | else: 126 | printRev(node.next) 127 | print(node.data) 128 | 129 | print("========No. 2c)========") 130 | print("Recursively Printing Linked List Elems:") 131 | printRev(ll_n1) 132 | print() 133 | 134 | # ======================== Task 03 ============================= 135 | def hocBuilder(height): 136 | if (height < 1): 137 | return 0 138 | elif (height == 1): 139 | return 8 140 | else: 141 | return 5 + hocBuilder(height - 1) 142 | 143 | print("========No. 3)========") 144 | print("hocBuilder(5) ->" , end=" ") 145 | print(hocBuilder(5)) 146 | print() 147 | 148 | # ========================= Task 04 ============================== 149 | # ========= 4a) : pattern printing using recursion ========== 150 | 151 | def printPattern(m): 152 | if (m == 0): 153 | print(" ") 154 | else: 155 | printPattern(m-1) 156 | printSeq(m) 157 | 158 | def printSeq(m): 159 | if (m == 0): 160 | print(" ") 161 | else: 162 | printSeq(m-1) 163 | print(m,end=" ") 164 | 165 | print("========No. 4a)========") 166 | printPattern(5) 167 | print("\n") 168 | 169 | # ======== 4b): Pattern printing ================== 170 | 171 | def pattern(m, n): 172 | 173 | if (m == 0): 174 | return 175 | 176 | printSpace(m - 1) 177 | printSeq2(n - m + 1) 178 | print() 179 | 180 | pattern(m - 1, n) 181 | 182 | def printSpace(m): 183 | 184 | if (m == 0): 185 | return 186 | 187 | print(" ", end=" ") 188 | printSpace(m - 1) 189 | 190 | def printSeq2(m): 191 | 192 | if (m == 0): 193 | return 194 | 195 | printSeq2(m - 1) 196 | print(m, end =" ") 197 | 198 | print("========No. 4a)========") 199 | print() 200 | pattern(5,5) 201 | print() 202 | 203 | # ====================== Task 05 ========================= 204 | class FinalQ: 205 | 206 | def print(self,array,idx): 207 | if(idx 25000 and investment <= 100000): 217 | return 45 + self.calcProfit(investment-1000) 218 | elif (investment > 100000): 219 | return 80 + self.calcProfit(investment-1000) 220 | else: 221 | return 0 222 | 223 | print("========No. 5)========") 224 | array = [25000,100000,250000,350000] 225 | f = FinalQ() 226 | f.print(array,0) 227 | -------------------------------------------------------------------------------- /Lab Assignment Solutions/Spring 2022/Assignment 02/Problem 02.py: -------------------------------------------------------------------------------- 1 | # Problem -02 2 | 3 | 4 | class Node: 5 | def __init__(self, element=None): 6 | self.element = element 7 | self.next = None 8 | 9 | 10 | class LinkedList: 11 | 12 | # No. 1(a) 13 | def __init__(self, arr: list) -> None: 14 | self.head = None 15 | 16 | for element in arr: 17 | node = Node(element) 18 | 19 | if self.head == None: 20 | self.head = node 21 | node = self.head 22 | continue 23 | 24 | current = self.head 25 | while current.next is not None: 26 | current = current.next 27 | 28 | current.next = node 29 | 30 | def len(self) -> int: 31 | 32 | lenght: int = 0 33 | current: Node = self.head 34 | while current is not None: 35 | lenght += 1 36 | current = current.next 37 | 38 | return lenght 39 | 40 | # No. 2 41 | def showList(self) -> None: 42 | 43 | current: Node = self.head 44 | 45 | if current != None: 46 | while current is not None: 47 | if current.next == None: 48 | print(current.element) 49 | else: 50 | print(current.element, end=" -> ") 51 | 52 | current = current.next 53 | else: 54 | print("Empty List") 55 | 56 | # No. 3 57 | def isEmpty(self) -> bool: 58 | if self.len() > 0: 59 | return False 60 | else: 61 | return True 62 | 63 | # No. 4 64 | def clear(self) -> None: 65 | 66 | current: Node = self.head 67 | while current is not None: 68 | current.element = None 69 | current = current.next 70 | 71 | self.head = None 72 | 73 | # No. 5 74 | def insert(self, newElement) -> None: 75 | 76 | node: Node = Node(newElement) 77 | 78 | current: Node = self.head 79 | if current is None: 80 | self.head = node 81 | node = self.head 82 | 83 | else: 84 | while current is not None: 85 | if current.element == newElement: 86 | print("Element already Exists") 87 | return 88 | 89 | if current.next == None: 90 | break 91 | else: 92 | current = current.next 93 | 94 | current.next = node 95 | 96 | # No. 6 97 | def insert_with_index(self, newElement, index: int) -> None: 98 | if index >= 0 and index < self.len(): 99 | 100 | current: Node = self.head 101 | while current is not None: 102 | if current.element == newElement: 103 | print("Element already Exists") 104 | return 105 | 106 | current = current.next 107 | 108 | node: Node = Node(newElement) 109 | 110 | if index == 0: 111 | node.next = self.head 112 | self.head = node 113 | 114 | elif index == self.len() - 1: 115 | current = self.head 116 | while current.next is not None: 117 | current = current.next 118 | current.next = node 119 | 120 | else: 121 | counter = 0 122 | current = self.head 123 | while current is not None: 124 | if counter == index - 1: 125 | next = current.next 126 | current.next = node 127 | node.next = next 128 | 129 | counter += 1 130 | current = current.next 131 | 132 | else: 133 | print("Invalid Index") 134 | return 135 | 136 | # No. 7 137 | def remove(self, delete_key): 138 | 139 | current = self.head 140 | prev = self.head 141 | counter = 0 142 | 143 | while current is not None: 144 | if current.element == delete_key: 145 | if current == self.head: 146 | self.head = self.head.next 147 | return current.element 148 | 149 | else: 150 | prev.next = current.next 151 | return current.element 152 | 153 | current = current.next 154 | 155 | if counter > 0: 156 | prev = prev.next 157 | 158 | counter += 1 159 | 160 | 161 | def main(): 162 | MyList = LinkedList([1, 2, 3, 4]) 163 | ListToClear = LinkedList([1, 2, 3, 4, 5]) 164 | EmptyList = LinkedList([]) 165 | ############--No. 01 & No. 2--############### 166 | print() 167 | print("*No. 1(a) & 2 -->") 168 | print("LinkedList from [1, 2, 3, 4] ====> ", end="") 169 | MyList.showList() 170 | print("LinkedList from [] ====> ", end="") 171 | EmptyList.showList() 172 | print("\n") 173 | print() 174 | ###############--No. 03--############### 175 | print("*No. 3 -->") 176 | print(f"Is 1 -> 2 -> 3 -> 4 Empty? ====> {MyList.isEmpty()}") 177 | MyList.isEmpty() 178 | print(f"Is [] Empty? ====> {EmptyList.isEmpty()}") 179 | print("\n") 180 | print() 181 | ###############--No. 04--############### 182 | print("*No. 4 -->") 183 | print("Clearing 1 -> 2 -> 3 -> 4 -> 5 ====> ", end="") 184 | ListToClear.clear() 185 | ListToClear.showList() 186 | print("\n") 187 | print() 188 | ###############--No. 05--############### 189 | print("*No. 5 -->") 190 | print("Inserting 5 into 1 -> 2 -> 3 -> 4 ====> ", end="") 191 | MyList.insert(5) 192 | MyList.showList() 193 | print() 194 | print("Inserting 2 into 1 -> 2 -> 3 -> 4 -> 5 ====> ", end="") 195 | MyList.insert(5) 196 | print("\n") 197 | print() 198 | ###############--No. 06--############### 199 | print("*No. 6 -->") 200 | print("Inserting value 1 in index 1 of 1 -> 2 -> 3 -> 4 -> 5 ====> ", end="") 201 | MyList.insert_with_index(1, 1) 202 | print() 203 | print("Inserting value 6 in index 7 of 1 -> 2 -> 3 -> 4 -> 5 ====> ", end="") 204 | MyList.insert_with_index(6, 8) 205 | print() 206 | print("Inserting value 0 in index 0 of 1 -> 2 -> 3 -> 4 -> 5 ====> ", end="") 207 | MyList.insert_with_index(0, 0) 208 | MyList.showList() 209 | print() 210 | print("Inserting value 3.5 in index 4 of 0 -> 1 -> 2 -> 3 -> 4 -> 5 ====> ", end="") 211 | MyList.insert_with_index(3.5, 4) 212 | MyList.showList() 213 | print() 214 | print( 215 | "Inserting value 6 in index 6 of 0 -> 1 -> 2 -> 3 -> 3.5 -> 4 -> 5 ====> ", 216 | end="", 217 | ) 218 | MyList.insert_with_index(6, 6) 219 | MyList.showList() 220 | print("\n") 221 | print() 222 | ###############--No. 07--################ 223 | print("*No. 7 -->") 224 | print("Removing 3.5 from 0 -> 1 -> 2 -> 3 -> 3.5 -> 4 -> 5 -> 6 ====> ", end="") 225 | MyList.remove(3.5) 226 | MyList.showList() 227 | print() 228 | 229 | 230 | if __name__ == "__main__": 231 | main() 232 | -------------------------------------------------------------------------------- /Lab Assignment Solutions/Fall 2022/Assignment 07/Searching -Sorting-Hashing.py: -------------------------------------------------------------------------------- 1 | # ================================ Searching & Sorting ================================ 2 | 3 | 4 | def findMaxValue(list): 5 | val = list[0] 6 | for i in list: 7 | if val < abs(i): 8 | val = abs(i) 9 | return val 10 | 11 | 12 | class KeyIndex: 13 | def __init__(self, arr): 14 | 15 | self.maxValue = findMaxValue(arr) 16 | 17 | self.aux = [0] * ((self.maxValue * 2) + 1) 18 | 19 | for i in arr: 20 | if self.aux[self.maxValue + i] == 0: 21 | self.aux[self.maxValue + i] = 1 22 | else: 23 | self.aux[self.maxValue + i] = self.aux[self.maxValue + i] + 1 24 | 25 | def search(self, key): 26 | key = int(key) 27 | 28 | if key + self.maxValue < 0 or key + self.maxValue >= len(self.aux): 29 | return False 30 | else: 31 | if self.aux[key + self.maxValue] != 0: 32 | return True 33 | else: 34 | return False 35 | 36 | def sort(self): 37 | index = 0 38 | 39 | arrSize = 0 40 | for item in self.aux: 41 | arrSize += item 42 | 43 | arr = [0] * arrSize 44 | 45 | for i in range(0, len(self.aux)): 46 | if index >= len(arr): 47 | print(arr) 48 | break 49 | 50 | if self.aux[i] >= 1: 51 | for _ in range(0, self.aux[i]): 52 | arr[index] = i - self.maxValue 53 | index += 1 54 | 55 | return arr 56 | 57 | 58 | # ================================ Searching & Sorting Testing ================================ 59 | print("================ Searching & Sorting ================\n") 60 | 61 | list = [-5, 8, 4, 6, 1, -8, -10] 62 | print(f"Given Array: {list}") 63 | 64 | key_indx = KeyIndex(list) 65 | print("") 66 | 67 | # Searching 68 | try: 69 | var = 4 70 | # var = int(input("Search for : ")) 71 | print(f"Searing for -> {var}") 72 | except ValueError: 73 | var = 3 74 | print( 75 | "User didn't manually entered the search value. Searching for default value 3.\n" 76 | ) 77 | 78 | if key_indx.search(var): 79 | print(f"{var} is in the list.\n") 80 | else: 81 | print(f"{var} is not in the list.\n") 82 | 83 | # Sorting 84 | print("Sorted List -> ", end="") 85 | key_indx.sort() 86 | print() 87 | 88 | # ================================ Hashtable ================================ 89 | 90 | # I've implemented the debug_mode because I was bored :3 . It's Not related to the task. 91 | # I've added / commented the same code at the end without the debug_mode. Also, it's by default 92 | # Turned off. But If you don't like the print statements inside the code Please uncomment the 93 | # Clean code / code without debug mode. Thank you :) 94 | 95 | 96 | class Hashtable: 97 | def __init__(self, size=9, debug_mode=False) -> None: 98 | self.size = size 99 | self.table = [0] * size 100 | 101 | # Debug Mode Flag for turning on/off some 102 | # print statements to help debugging 103 | self.debug_mode = debug_mode 104 | if debug_mode: 105 | print(f"\n[DEBUG MODE] Created Hashtable with Size - {self.size}\n") 106 | 107 | def hashKey(self, string): 108 | 109 | vowels = "AEIOUaeiou" 110 | digits = "0123456789" 111 | 112 | total_consonant = 0 113 | digit_sum = 0 114 | 115 | for char in string: 116 | # If char is consonant 117 | if char not in vowels and char not in digits: 118 | total_consonant += 1 119 | 120 | elif char.isdigit(): 121 | digit_sum += int(char) 122 | 123 | hash_key = (total_consonant * 24) + digit_sum 124 | return hash_key 125 | 126 | def insert(self, string): 127 | 128 | hash_key = self.hashKey(string) 129 | position = hash_key % self.size 130 | 131 | if self.debug_mode: 132 | print( 133 | f"[DEBUG MODE] String - {string}\n[DEBUG MODE] HashKey - {hash_key}\n[DEBUG MODE] Position - {position}" 134 | ) 135 | 136 | # Loop start from 1 because we need to add 1 137 | # with hashkey every iteration 138 | for index in range(1, self.size): 139 | if self.table[position] == 0: 140 | self.table[position] = string 141 | 142 | if self.debug_mode: 143 | print(f"[DEBUG MODE] String inserted in Position - {position}") 144 | print(f"[DEBUG MODE] Current HashTable -> \n{self.table}\n\n") 145 | 146 | break 147 | 148 | else: 149 | position = (hash_key + index) % self.size 150 | 151 | if self.debug_mode: 152 | print( 153 | f"> Current Position is not empty. New Position -> {position}" 154 | ) 155 | 156 | def print(self): 157 | print("Printing Hashtable -> \n") 158 | 159 | for string in range(self.size): 160 | print(self.table[string]) 161 | 162 | 163 | # ================================ Hashtable Testing ================================ 164 | print("================ Hashtable & Hashing ================\n") 165 | 166 | strings = [ 167 | "ST1E89B8A32", 168 | "ZJO9V49NDOU", 169 | "X9ZAR2JD6F7", 170 | "KD9LNX46TT2", 171 | "G94F5SMC2DG", 172 | "5YLHRBO79CT", 173 | "WN2NY54F22D", 174 | "YVRFKVUOH6Y", 175 | "5W8UWJSDCJH", 176 | ] 177 | 178 | hash_table = Hashtable(debug_mode=False) 179 | 180 | for string in strings: 181 | hash_table.insert(string) 182 | 183 | hash_table.print() 184 | 185 | 186 | # =============================== Hashing Without Debug Mode ============================ 187 | # 188 | # 189 | # class Hashtable: 190 | # def __init__(self, size=9) -> None: 191 | # self.size = size 192 | # self.table = [0] * size 193 | 194 | # def hashKey(self, string): 195 | 196 | # vowels = "AEIOUaeiou" 197 | # digits = "0123456789" 198 | 199 | # total_consonant = 0 200 | # digit_sum = 0 201 | 202 | # for char in string: 203 | # # If char is consonant 204 | # if char not in vowels and char not in digits: 205 | # total_consonant += 1 206 | 207 | # elif char.isdigit(): 208 | # digit_sum += int(char) 209 | 210 | # hash_key = (total_consonant * 24) + digit_sum 211 | # return hash_key 212 | 213 | # def insert(self, string): 214 | 215 | # hash_key = self.hashKey(string) 216 | # position = hash_key % self.size 217 | 218 | # # Loop start from 1 because we need to add 1 219 | # # with hashkey every iteration 220 | # for index in range(1, self.size): 221 | # if self.table[position] == 0: 222 | # self.table[position] = string 223 | # break 224 | 225 | # else: 226 | # position = (hash_key + index) % self.size 227 | 228 | # def print(self): 229 | # print("Printing Hashtable -> \n") 230 | 231 | # for string in range(self.size): 232 | # print(self.table[string]) 233 | 234 | 235 | # print("================ Hashtable & Hashing ================\n") 236 | 237 | # strings = [ 238 | # "ST1E89B8A32", 239 | # "ZJO9V49NDOU", 240 | # "X9ZAR2JD6F7", 241 | # "KD9LNX46TT2", 242 | # "G94F5SMC2DG", 243 | # "5YLHRBO79CT", 244 | # "WN2NY54F22D", 245 | # "YVRFKVUOH6Y", 246 | # "5W8UWJSDCJH", 247 | # ] 248 | 249 | # hash_table = Hashtable() 250 | 251 | 252 | # for string in strings: 253 | # hash_table.insert(string) 254 | 255 | # hash_table.print() 256 | -------------------------------------------------------------------------------- /Lab Assignment Solutions/Fall 2022/Assignment 07/Lab07_21101048.txt: -------------------------------------------------------------------------------- 1 | z# ========Lab 07============ 2 | # Name: Mirza Mahrab Hossain Rudra 3 | # Student ID: 21101048 4 | # Section 15 5 | # ========================== 6 | 7 | # ================================ Searching & Sorting ================================ 8 | 9 | 10 | def findMaxValue(list): 11 | val = list[0] 12 | for i in list: 13 | if val < abs(i): 14 | val = abs(i) 15 | return val 16 | 17 | 18 | class KeyIndex: 19 | def __init__(self, arr): 20 | 21 | self.maxValue = findMaxValue(arr) 22 | 23 | self.aux = [0] * ((self.maxValue * 2) + 1) 24 | 25 | for i in arr: 26 | if self.aux[self.maxValue + i] == 0: 27 | self.aux[self.maxValue + i] = 1 28 | else: 29 | self.aux[self.maxValue + i] = self.aux[self.maxValue + i] + 1 30 | 31 | def search(self, key): 32 | key = int(key) 33 | 34 | if key + self.maxValue < 0 or key + self.maxValue >= len(self.aux): 35 | return False 36 | else: 37 | if self.aux[key + self.maxValue] != 0: 38 | return True 39 | else: 40 | return False 41 | 42 | def sort(self): 43 | index = 0 44 | 45 | arrSize = 0 46 | for item in self.aux: 47 | arrSize += item 48 | 49 | arr = [0] * arrSize 50 | 51 | for i in range(0, len(self.aux)): 52 | if index >= len(arr): 53 | print(arr) 54 | break 55 | 56 | if self.aux[i] >= 1: 57 | for _ in range(0, self.aux[i]): 58 | arr[index] = i - self.maxValue 59 | index += 1 60 | 61 | return arr 62 | 63 | 64 | # ================================ Searching & Sorting Testing ================================ 65 | print("================ Searching & Sorting ================\n") 66 | 67 | list = [-5, 8, 4, 6, 1, -8, -10] 68 | print(f"Given Array: {list}") 69 | 70 | key_indx = KeyIndex(list) 71 | print("") 72 | 73 | # Searching 74 | try: 75 | var = 4 76 | # var = int(input("Search for : ")) 77 | print(f"Searing for -> {var}") 78 | except ValueError: 79 | var = 3 80 | print( 81 | "User didn't manually entered the search value. Searching for default value 3.\n" 82 | ) 83 | 84 | if key_indx.search(var): 85 | print(f"{var} is in the list.\n") 86 | else: 87 | print(f"{var} is not in the list.\n") 88 | 89 | # Sorting 90 | print("Sorted List -> ", end="") 91 | key_indx.sort() 92 | print() 93 | 94 | # ================================ Hashtable ================================ 95 | 96 | # I've implemented the debug_mode because I was bored :3 . It's Not related to the task. 97 | # I've added / commented the same code at the end without the debug_mode. Also, it's by default 98 | # Turned off. But If you don't like the print statements inside the code Please uncomment the 99 | # Clean code / code without debug mode. Thank you :) 100 | 101 | 102 | class Hashtable: 103 | def __init__(self, size=9, debug_mode=False) -> None: 104 | self.size = size 105 | self.table = [0] * size 106 | 107 | # Debug Mode Flag for turning on/off some 108 | # print statements to help debugging 109 | self.debug_mode = debug_mode 110 | if debug_mode: 111 | print(f"\n[DEBUG MODE] Created Hashtable with Size - {self.size}\n") 112 | 113 | def hashKey(self, string): 114 | 115 | vowels = "AEIOUaeiou" 116 | digits = "0123456789" 117 | 118 | total_consonant = 0 119 | digit_sum = 0 120 | 121 | for char in string: 122 | # If char is consonant 123 | if char not in vowels and char not in digits: 124 | total_consonant += 1 125 | 126 | elif char.isdigit(): 127 | digit_sum += int(char) 128 | 129 | hash_key = (total_consonant * 24) + digit_sum 130 | return hash_key 131 | 132 | def insert(self, string): 133 | 134 | hash_key = self.hashKey(string) 135 | position = hash_key % self.size 136 | 137 | if self.debug_mode: 138 | print( 139 | f"[DEBUG MODE] String - {string}\n[DEBUG MODE] HashKey - {hash_key}\n[DEBUG MODE] Position - {position}" 140 | ) 141 | 142 | # Loop start from 1 because we need to add 1 143 | # with hashkey every iteration 144 | for index in range(1, self.size): 145 | if self.table[position] == 0: 146 | self.table[position] = string 147 | 148 | if self.debug_mode: 149 | print(f"[DEBUG MODE] String inserted in Position - {position}") 150 | print(f"[DEBUG MODE] Current HashTable -> \n{self.table}\n\n") 151 | 152 | break 153 | 154 | else: 155 | position = (hash_key + index) % self.size 156 | 157 | if self.debug_mode: 158 | print( 159 | f"> Current Position is not empty. New Position -> {position}" 160 | ) 161 | 162 | def print(self): 163 | print("Printing Hashtable -> \n") 164 | 165 | for string in range(self.size): 166 | print(self.table[string]) 167 | 168 | 169 | # ================================ Hashtable Testing ================================ 170 | print("================ Hashtable & Hashing ================\n") 171 | 172 | strings = [ 173 | "ST1E89B8A32", 174 | "ZJO9V49NDOU", 175 | "X9ZAR2JD6F7", 176 | "KD9LNX46TT2", 177 | "G94F5SMC2DG", 178 | "5YLHRBO79CT", 179 | "WN2NY54F22D", 180 | "YVRFKVUOH6Y", 181 | "5W8UWJSDCJH", 182 | ] 183 | 184 | hash_table = Hashtable(debug_mode=False) 185 | 186 | for string in strings: 187 | hash_table.insert(string) 188 | 189 | hash_table.print() 190 | 191 | 192 | # =============================== Hashing Without Debug Mode ============================ 193 | # 194 | # 195 | # class Hashtable: 196 | # def __init__(self, size=9) -> None: 197 | # self.size = size 198 | # self.table = [0] * size 199 | 200 | # def hashKey(self, string): 201 | 202 | # vowels = "AEIOUaeiou" 203 | # digits = "0123456789" 204 | 205 | # total_consonant = 0 206 | # digit_sum = 0 207 | 208 | # for char in string: 209 | # # If char is consonant 210 | # if char not in vowels and char not in digits: 211 | # total_consonant += 1 212 | 213 | # elif char.isdigit(): 214 | # digit_sum += int(char) 215 | 216 | # hash_key = (total_consonant * 24) + digit_sum 217 | # return hash_key 218 | 219 | # def insert(self, string): 220 | 221 | # hash_key = self.hashKey(string) 222 | # position = hash_key % self.size 223 | 224 | # # Loop start from 1 because we need to add 1 225 | # # with hashkey every iteration 226 | # for index in range(1, self.size): 227 | # if self.table[position] == 0: 228 | # self.table[position] = string 229 | # break 230 | 231 | # else: 232 | # position = (hash_key + index) % self.size 233 | 234 | # def print(self): 235 | # print("Printing Hashtable -> \n") 236 | 237 | # for string in range(self.size): 238 | # print(self.table[string]) 239 | 240 | 241 | # print("================ Hashtable & Hashing ================\n") 242 | 243 | # strings = [ 244 | # "ST1E89B8A32", 245 | # "ZJO9V49NDOU", 246 | # "X9ZAR2JD6F7", 247 | # "KD9LNX46TT2", 248 | # "G94F5SMC2DG", 249 | # "5YLHRBO79CT", 250 | # "WN2NY54F22D", 251 | # "YVRFKVUOH6Y", 252 | # "5W8UWJSDCJH", 253 | # ] 254 | 255 | # hash_table = Hashtable() 256 | 257 | 258 | # for string in strings: 259 | # hash_table.insert(string) 260 | 261 | # hash_table.print() 262 | -------------------------------------------------------------------------------- /Lab Assignment Solutions/Fall 2022/Assignment 04/DoublyLinkedList.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self, e, n, p): 3 | self.element = e 4 | self.next = n 5 | self.prev = p 6 | 7 | 8 | class DoublyList: 9 | def __init__(self, arr): 10 | # Design the constructor based on data type of a. If 'a' is built in python list then 11 | # Creates a linked list using the values from the given array. 12 | 13 | # Creating a DummyHead 14 | self.dummyHead = Node(None, None, None) 15 | # Creting DummyHeaded Doubly circular LinkedList 16 | self.dummyHead.prev = self.dummyHead.next = self.dummyHead 17 | 18 | if type(arr) == Node: 19 | 20 | self.dummyHead.next = arr 21 | arr.prev = self.dummyHead 22 | 23 | self.dummyHead.prev = arr 24 | arr.next = self.dummyHead 25 | 26 | else: 27 | 28 | elem = arr[0] 29 | tail = Node(elem, None, None) 30 | 31 | self.dummyHead.next = tail 32 | tail.prev = self.dummyHead 33 | 34 | self.dummyHead.prev = tail 35 | tail.next = self.dummyHead 36 | 37 | head = self.dummyHead 38 | 39 | for i in range(1, len(arr)): 40 | 41 | newNode = Node(arr[i], None, None) 42 | 43 | # add newNode & tail 44 | # then make the newNode a newTail 45 | newNode.prev = tail 46 | tail.next = newNode 47 | tail = newNode 48 | 49 | # make the LinkedList circular 50 | head.prev = tail 51 | tail.next = head 52 | 53 | # Counts the number of Nodes in the list 54 | def countNode(self): 55 | 56 | counter = 0 57 | 58 | head = self.dummyHead 59 | current = head.next 60 | 61 | while current != head: 62 | current = current.next 63 | counter += 1 64 | 65 | return counter 66 | 67 | # prints the elements in the list 68 | def forwardprint(self): 69 | 70 | head = self.dummyHead 71 | tail = head.next 72 | 73 | while tail != head: 74 | 75 | if tail.next == head: 76 | print(tail.element) 77 | 78 | else: 79 | print(tail.element, end=", ") 80 | 81 | tail = tail.next 82 | 83 | # prints the elements in the list backward 84 | def backwardprint(self): 85 | 86 | head = self.dummyHead 87 | tail = head.prev 88 | 89 | while tail != head: 90 | if tail.prev == head: 91 | print(tail.element) 92 | 93 | else: 94 | print(tail.element, end=", ") 95 | 96 | tail = tail.prev 97 | 98 | # returns the reference of the at the given index. For invalid index return None. 99 | def nodeAt(self, idx): 100 | 101 | counter = 0 102 | nodeCount = self.countNode() 103 | 104 | head = self.dummyHead 105 | tail = head.next 106 | 107 | # Index Validation 108 | if idx >= nodeCount or idx < 0: 109 | return None 110 | 111 | # We don't need loop to determine these 112 | if idx == nodeCount: 113 | return head.prev 114 | 115 | elif idx == 0: 116 | return tail 117 | 118 | else: 119 | while tail != head: 120 | if counter == idx: 121 | return tail 122 | 123 | tail = tail.next 124 | counter += 1 125 | 126 | # returns the index of the containing the given element. 127 | # if the element does not exist in the List, return -1. 128 | def indexOf(self, elem): 129 | 130 | head = self.dummyHead 131 | tail = head.next 132 | index = 0 133 | 134 | while tail != head: 135 | 136 | if tail.element == elem: 137 | return index 138 | 139 | tail = tail.next 140 | index += 1 141 | 142 | return -1 143 | 144 | # inserts containing the given element at the given index Check validity of index. 145 | def insert(self, elem, idx): 146 | 147 | head = self.dummyHead 148 | tail = head.next 149 | counter = 0 150 | 151 | # Index Validation 152 | if idx >= self.countNode() + 1 or idx < 0: 153 | return None 154 | 155 | newNode = Node(elem, None, None) 156 | 157 | while tail != head: 158 | 159 | if counter == idx: 160 | 161 | pred = tail.prev 162 | 163 | newNode.next = tail 164 | newNode.prev = pred 165 | 166 | pred.next = newNode 167 | tail.prev = newNode 168 | 169 | tail = tail.next 170 | counter += 1 171 | 172 | # removes at the given index. returns element of the removed node. 173 | # Check validity of index. return None if index is invalid. 174 | def remove(self, idx): 175 | 176 | head = self.dummyHead 177 | tail = head.next 178 | counter = 0 179 | 180 | # Index Validation 181 | if idx >= self.countNode() or idx < 0: 182 | return None 183 | 184 | while tail != head: 185 | if counter == idx: 186 | 187 | predNode = tail.prev 188 | nextNode = tail.next 189 | 190 | predNode.next = nextNode 191 | nextNode.prev = predNode 192 | 193 | removed = tail.element 194 | 195 | # Garbage Collection 196 | tail.prev = tail.next = None 197 | tail.element = None 198 | # tail = None 199 | 200 | return str(removed) 201 | 202 | tail = tail.next 203 | counter += 1 204 | 205 | 206 | print("/// Test 01 ///") 207 | a1 = [10, 20, 30, 40] 208 | h1 = DoublyList(a1) # Creates a linked list using the values from the array 209 | 210 | h1.forwardprint() # This should print: 10,20,30,40. 211 | h1.backwardprint() # This should print: 40,30,20,10. 212 | print(h1.countNode()) # This should print: 4 213 | 214 | print("/// Test 02 ///") 215 | # returns the reference of the at the given index. For invalid idx return None. 216 | myNode = h1.nodeAt(2) 217 | print( 218 | myNode.element 219 | ) # This should print: 30. In case of invalid index This will print "index error" 220 | 221 | print("/// Test 03 ///") 222 | # returns the index of the containing the given element. if the element does not exist in the List, return -1. 223 | index = h1.indexOf(40) 224 | print(index) # This should print: 3. In case of element that 225 | # doesn't exists in the list this will print -1. 226 | 227 | print("/// Test 04 ///") 228 | 229 | a2 = [10, 20, 30, 40] 230 | h2 = DoublyList(a2) # uses the constructor 231 | h2.forwardprint() # This should print: 10,20,30,40. 232 | 233 | # inserts containing the given element at the given index. Check validity of index. 234 | h2.insert(85, 0) 235 | h2.forwardprint() # This should print: 85,10,20,30,40. 236 | h2.backwardprint() # This should print: 40,30,20,10,85. 237 | 238 | print() 239 | h2.insert(95, 3) 240 | h2.forwardprint() # This should print: 85,10,20,95,30,40. 241 | h2.backwardprint() # This should print: 40,30,95,20,10,80. 242 | 243 | print() 244 | h2.insert(75, 6) 245 | h2.forwardprint() # This should print: 85,10,20,95,30,40,75. 246 | h2.backwardprint() # This should print: 75,40,30,95,20,10,85. 247 | 248 | 249 | print("/// Test 05 ///") 250 | a3 = [10, 20, 30, 40, 50, 60, 70] 251 | h3 = DoublyList(a3) # uses the constructor 252 | h3.forwardprint() # This should print: 10,20,30,40,50,60,70. 253 | 254 | # removes at the given index. returns element of the removed node. Check validity of index. return None if index is invalid. 255 | print("Removed element: " + h3.remove(0)) # This should print: Removed element: 10 256 | h3.forwardprint() # This should print: 20,30,40,50,60,70. 257 | h3.backwardprint() # This should print: 70,60,50,40,30,20. 258 | print("Removed element: " + h3.remove(3)) # This should print: Removed element: 50 259 | h3.forwardprint() # This should print: 20,30,40,60,70. 260 | h3.backwardprint() # This should print: 70,60,40,30,20. 261 | print("Removed element: " + h3.remove(4)) # This should print: Removed element: 70 262 | h3.forwardprint() # This should print: 20,30,40,60. 263 | h3.backwardprint() # This should print: 60,40,30,20. 264 | -------------------------------------------------------------------------------- /Lab Assignment Solutions/Fall 2022/Assignment 02/Lab02_21101048.txt: -------------------------------------------------------------------------------- 1 | # ========Lab 02============ 2 | # Name: Mirza Mahrab Hossain Rudra 3 | # Student ID: 21101048 4 | # Section 15 5 | # ========================== 6 | 7 | 8 | class CircularArray: 9 | def __init__(self, lin, st, sz): 10 | # Initializing Variables 11 | self.start = st 12 | self.size = sz 13 | self.cir = [None] * len(lin) 14 | 15 | # if lin = [10, 20, 30, 40, None] 16 | # then, CircularArray(lin, 2, 4) will generate 17 | # cir = [40, null, 10, 20, 30] 18 | 19 | # To Do. 20 | # Hints: set the values for initialized variables 21 | 22 | index = self.start 23 | 24 | for i in range(len(lin)): 25 | self.cir[index] = lin[i] 26 | index = (index + 1) % len(self.cir) 27 | 28 | # Print from index 0 to len(cir) - 1 29 | def printFullLinear(self): # Easy 30 | # To Do 31 | 32 | for i in range(len(self.cir)): 33 | if i == len(self.cir) - 1: 34 | print(self.cir[i]) 35 | else: 36 | print(self.cir[i], end=", ") 37 | 38 | # Print from start index and total size elements 39 | def printForward(self): # Easy 40 | # To Do 41 | 42 | index = self.start 43 | 44 | for i in range(self.size): 45 | if i == self.size - 1: 46 | print(self.cir[index]) 47 | else: 48 | print(self.cir[index], end=", ") 49 | 50 | index = (index + 1) % len(self.cir) 51 | 52 | def printBackward(self): # Easy 53 | # To Do 54 | 55 | index = (self.start + self.size - 1) % len(self.cir) 56 | 57 | for i in range(self.size): 58 | if i == self.size - 1: 59 | print(self.cir[index]) 60 | else: 61 | print(self.cir[index], end=", ") 62 | 63 | index -= 1 64 | if index < 0: 65 | index = len(self.cir) - 1 66 | 67 | # With no null cells 68 | def linearize(self): # Medium 69 | # To Do 70 | 71 | l = [None] * (self.size) 72 | index = self.start 73 | 74 | i = 0 75 | while i < self.size: 76 | l[i] = self.cir[index] 77 | index = (index + 1) % len(self.cir) 78 | i += 1 79 | 80 | self.cir = l 81 | 82 | # Do not change the Start index 83 | def resizeStartUnchanged(self, newcapacity): # Medium 84 | # To Do 85 | newCircular = [None] * newcapacity 86 | 87 | index = self.start 88 | s = self.start 89 | for i in range(self.size): 90 | newCircular[index] = self.cir[s] 91 | index = index + 1 92 | s = (s + 1) % len(self.cir) 93 | 94 | self.cir = newCircular 95 | 96 | # This method will check whether the array is palindrome or not 97 | def palindromeCheck(self): # Hard 98 | # To Do 99 | 100 | flag = False 101 | 102 | index = self.start 103 | j = (self.start + self.size - 1) % len(self.cir) 104 | 105 | for i in range(self.size // 2): 106 | 107 | if self.cir[index] == self.cir[j]: 108 | flag = True 109 | else: 110 | flag = False 111 | break 112 | 113 | index = (index + 1) % len(self.cir) 114 | 115 | j = j - 1 116 | if j < 0: 117 | j = len(self.cir) - 1 118 | 119 | if flag == True: 120 | print("This array is a palindrome") 121 | else: 122 | print("This array is NOT a palindrome") 123 | 124 | # This method will sort the values by keeping the start unchanged 125 | def sort(self): 126 | # To Do 127 | 128 | for i in range(self.size): 129 | 130 | for j in range(i + 1, self.size): 131 | 132 | x = (i + self.start) % len(self.cir) 133 | y = (j + self.start) % len(self.cir) 134 | 135 | if self.cir[x] > self.cir[y]: 136 | 137 | temp = self.cir[x] 138 | self.cir[x] = self.cir[y] 139 | self.cir[y] = temp 140 | 141 | # This method will check the given array across the base array and if they are equivalent interms of values return true, or else return false 142 | def equivalent(self, cir_arr): 143 | # To Do 144 | isEqual = False 145 | idx1 = self.start 146 | idx2 = cir_arr.start 147 | 148 | if self.size != cir_arr.size: 149 | isEqual = False 150 | return isEqual 151 | 152 | else: 153 | for _ in range(self.size): 154 | 155 | if self.cir[idx1] == cir_arr.cir[idx2]: 156 | isEqual = True 157 | 158 | idx1 = (idx1 + 1) % len(self.cir) 159 | idx2 = (idx2 + 1) % len(cir_arr.cir) 160 | 161 | else: 162 | isEqual = False 163 | return isEqual 164 | 165 | return isEqual 166 | 167 | # the method take another circular array and returns a linear array containing the common elements between the two circular arrays. 168 | def intersection(self, c2): 169 | # To Do 170 | 171 | cir1 = self.cir 172 | idx1 = self.start 173 | cir2 = c2.cir 174 | temp = [None] * self.size 175 | index3 = 0 176 | 177 | for i in range(self.size): 178 | idx2 = c2.start 179 | 180 | for j in range(c2.size): 181 | 182 | if cir1[idx1] == cir2[idx2]: 183 | temp[index3] = cir1[idx1] 184 | index3 += 1 185 | 186 | idx2 = (idx2 + 1) % len(cir2) 187 | idx1 = (idx1 + 1) % len(cir1) 188 | 189 | linear = [None] * index3 190 | for i in range(len(linear)): 191 | linear[i] = temp[i] 192 | 193 | return linear 194 | 195 | 196 | # Tester class. Run this cell after completing methods in the upper cell and 197 | # check the output 198 | 199 | 200 | lin_arr1 = [10, 20, 30, 40, None] 201 | 202 | 203 | print("==========Test 1==========") 204 | c1 = CircularArray(lin_arr1, 2, 4) 205 | c1.printFullLinear() # This should print: 40, None, 10, 20, 30 206 | c1.printForward() # This should print: 10, 20, 30, 40 207 | c1.printBackward() # This should print: 40, 30, 20, 10 208 | 209 | 210 | print("==========Test 2==========") 211 | c1.linearize() 212 | c1.printFullLinear() # This should print: 10, 20, 30, 40 213 | 214 | 215 | print("==========Test 3==========") 216 | lin_arr2 = [10, 20, 30, 40, 50] 217 | c2 = CircularArray(lin_arr2, 2, 5) 218 | c2.printFullLinear() # This should print: 40, 50, 10, 20, 30 219 | c2.resizeStartUnchanged(8) # parameter --> new Capacity 220 | c2.printFullLinear() # This should print: None, None, 10, 20, 30, 40, 50, None 221 | 222 | 223 | print("==========Test 4==========") 224 | lin_arr3 = [10, 20, 30, 20, 10, None, None] 225 | c3 = CircularArray(lin_arr3, 3, 5) 226 | c3.printForward() # This should print: 10, 20, 30, 20, 10 227 | c3.palindromeCheck() # This should print: This array is a palindrome 228 | 229 | 230 | print("==========Test 5==========") 231 | lin_arr4 = [10, 20, 30, 20, None, None, None] 232 | c4 = CircularArray(lin_arr4, 3, 4) 233 | c4.printForward() # This should print: 10, 20, 30, 20 234 | c4.palindromeCheck() # This should print: This array is NOT a palindrome 235 | 236 | 237 | print("==========Test 6==========") 238 | lin_arr5 = [10, 20, -30, 20, 50, 30, None] 239 | c5 = CircularArray(lin_arr5, 5, 6) 240 | c5.printForward() # This should print: 10, 20, -30, 20, 50, 30 241 | c5.sort() 242 | c5.printForward() # This should print: -30, 10, 20, 20, 30, 50 243 | 244 | 245 | print("==========Test 7==========") 246 | lin_arr6 = [10, 20, -30, 20, 50, 30, None] 247 | c6 = CircularArray(lin_arr6, 2, 6) 248 | c7 = CircularArray(lin_arr6, 5, 6) 249 | c6.printForward() # This should print: 10, 20, -30, 20, 50, 30 250 | c7.printForward() # This should print: 10, 20, -30, 20, 50, 30 251 | print(c6.equivalent(c7)) # This should print: True 252 | 253 | 254 | print("==========Test 8==========") 255 | lin_arr7 = [10, 20, -30, 20, 50, 30, None, None, None] 256 | c8 = CircularArray(lin_arr7, 8, 6) 257 | c6.printForward() # This should print: 10, 20, -30, 20, 50, 30 258 | c8.printForward() # This should print: 10, 20, -30, 20, 50, 30 259 | print(c6.equivalent(c8)) # This should print: True 260 | 261 | 262 | print("==========Test 9==========") 263 | lin_arr8 = [10, 20, 30, 40, 50, 60, None, None, None] 264 | c9 = CircularArray(lin_arr8, 8, 6) 265 | c6.printForward() # This should print: 10, 20, -30, 20, 50, 30 266 | c9.printForward() # This should print: 10, 20, 30, 40, 50, 60 267 | print(c6.equivalent(c9)) # This should print: False 268 | 269 | 270 | print("==========Test 10==========") 271 | lin_arr9 = [10, 20, 30, 40, 50, None, None, None] 272 | c10 = CircularArray(lin_arr9, 5, 5) 273 | c10.printFullLinear() # This should print: 40, 50, None, None, None, 10, 20, 30 274 | lin_arr10 = [5, 40, 15, 25, 10, 20, 5, None, None, None, None, None] 275 | c11 = CircularArray(lin_arr10, 8, 7) 276 | c11.printFullLinear() # This should print: 10, 20, 5, None, None, None, None, None, 5, 40, 15, 25 277 | output = c10.intersection(c11) 278 | print(output) # This should print: [10, 20, 40] 279 | -------------------------------------------------------------------------------- /Notes/Arrays.md: -------------------------------------------------------------------------------- 1 | # Introduction 2 | ## Types of Data Structures 3 | 4 | * Arrays 5 | * Linked Lists 6 | * Queues 7 | * Stacks 8 | 9 | ## Prerequisities 10 | * Linear Arrays ( `List` in Python ) 11 | * Objects and Classes (Good grip on the OOP concepts) 12 | 13 | # Arrays 14 | 15 | ## Linear Arrays 16 | 17 | * What is Linear Arrays? 18 | > An array is a collection of a fix number of items where all the items are of the same data type. 19 | 20 | * Arrays consist of : 21 | 22 | * **Element** - Each item stored in an array is called an element. 23 | * **Index** - Each location of an element in an array has a numerical value, which is used to access its corresponding element. 24 | 25 | Liner Array: 26 | 27 | Elements | 50 | 60 | 70 | 80 | 90 | 100 | 28 | | :---|---: | :---|---: | :---|---: | :--- 29 | Index | 0 | 1 | 2 | 3 | 4 | 5 | 30 | 31 | We can declare a liner array (in python a `list`), 32 | ```py 33 | arr = [0, 1, 2, 3, 4, 5] 34 | ``` 35 | This way an adress is created in the memory where the array is stored. We can see the memory location in Python3 with the `id()` and `hex()` methods. 36 | 37 | > `id()` -> prints the memroy adress of an object. 38 | > `hex()` -> converts the memory adress to hexadecimal representation. 39 | 40 | ```py 41 | >> print(hex(id(arr))) 42 | 0x7f3bec064ec0 43 | ``` 44 | So, whenever we're typing `arr`, we're not actually referencing the array itself. We're referencing a variable that has the reference of the memory location where the array is stored. 45 | 46 | ### Copying an array 47 | 48 | There are 3 ways we can copy arrays in Python: 49 | * Simply using the assignment operator 50 | * Shallow copy 51 | * Deep copy 52 | 53 | #### Using Assignment Operator 54 | We can use `=` to copy arrays. 55 | 56 | For example 57 | ```py 58 | new_arr = old_arr 59 | ``` 60 | ***Something to remember :*** 61 | > In python, Assignment statements don't copy objects, they create bindings between a target and an object. When we use `=` operator user may think that this creates a new object which it doesn't. It only creates a new variable that shares the reference of the origianl object. 62 | 63 | **Simply put, `new_arr = old_arr` just copy the adress of the `old_arr` to `new_arr`. So, no new array has been created in the memory. These `old_arr` and `new_arr` now points to the same adress in the memory.** 64 | 65 | For example, 66 | ```py 67 | arr1 = [2, 6, 9, 4] 68 | 69 | # Prints the address of the arr1 in the memory 70 | print(hex(id(arr1))) 71 | 72 | # assigning arr1 to arr2 73 | arr2 = arr1 74 | 75 | # Prints the address of the arr1 in the memory 76 | print(hex(id(arr2))) 77 | 78 | # making a change in arr1 79 | arr1[1] = 7 80 | 81 | # displaying the arrays 82 | >> print(arr1) 83 | >> print(arr2) 84 | 0x7f5dcf5d0e80 85 | 0x7f5dcf5d0e80 86 | [2, 7, 9, 4] 87 | [2, 7, 9, 4] 88 | ``` 89 | So you see, because the two array shares the same memory address, chaning the value in one array changes the other too. 90 | 91 | > Sometimes we want to have the original values unchanged and only modify the new values or vice varsa. In Python we can use the other two copy methods which are, 92 | 93 | * Shallow Copy 94 | * Deep Copy 95 | 96 | **To make these copy work, we use the `copy` module.** 97 | 98 | #### Shallow Copy 99 | > A shallow copy creates a new object which stores the refernce of the original elements. So, a shallow copy doesn't just copies the reference of nested objects. This means a copy process doesn't recurse or create copies of nested object itself. 100 | 101 | **In other words, a shallow copy can copy a normal list / array and store that in a different memory space. However, if the list is a nested list, the shallow copy method will only copy the whole list in a another memory location, however, it will not copy nested list objects. Instead it'll create the reference of origianl memory for the nested items.** 102 | 103 | For better understanding this, let's see an example, 104 | ```py 105 | import copy 106 | 107 | old_list = [1,2,3,4] 108 | new_list = copy.copy(old_list) 109 | 110 | new_list.append(5) 111 | 112 | print(f"Old list: {old_list}") 113 | print(f"Old list memory location: {hex(id(old_list))}") 114 | print(f"New list: {new_list}") 115 | print(f"New list memory location: {hex(id(new_list))}") 116 | ``` 117 | After running the program, we'll get, 118 | 119 | ```txt 120 | Old list: [1, 2, 3, 4] 121 | Old list memory location: 0x7f42452b8e00 122 | New list: [1, 2, 3, 4, 5] 123 | New list memory location: 0x7f42452b8480 124 | ``` 125 | So, with this method we can `copy` a list in python. However, this only **really** works with normal lists. We'll get into problems if we use this method to copy nested lists. 126 | 127 | For example, 128 | 129 | ```py 130 | import copy 131 | 132 | old_list = [[1,2,3],[4,5,6]] 133 | new_list = copy.copy(old_list) 134 | 135 | new_list[0] = ['a','b','c'] 136 | 137 | print(f"Old list: {old_list}") 138 | print(f"Old list memory location: {hex(id(old_list))}") 139 | print(f"New list: {new_list}") 140 | print(f"New list memory location: {hex(id(new_list))}") 141 | ``` 142 | Output: 143 | ```txt 144 | Old list: [[1, 2, 3], [4, 5, 6]] 145 | Old list memory location: 0x7f7df913c800 146 | New list: [['a', 'b', 'c'], [4, 5, 6]] 147 | New list memory location: 0x7f7df913c580 148 | ``` 149 | This works fine. Now, let's see what happens if we change the nested list objects inside the original list. 150 | 151 | ```py 152 | import copy 153 | 154 | old_list = [[1, 2, 3], [4, 5, 6]] 155 | new_list = copy.copy(old_list) 156 | 157 | new_list[0][0] = "a" 158 | 159 | print(f"Old list: {old_list}") 160 | print(f"Old list memory location: {hex(id(old_list))}") 161 | print(f"New list: {new_list}") 162 | print(f"New list memory location: {hex(id(new_list))}") 163 | ``` 164 | Output: 165 | 166 | ```txt 167 | Old list: [['a', 2, 3], [4, 5, 6]] 168 | Old list memory location: 0x7ff49810f900 169 | New list: [['a', 2, 3], [4, 5, 6]] 170 | New list memory location: 0x7ff49810f680 171 | ``` 172 | `old_list` and `new_list` both changes. This happen because, the `shallow copy` method only copy the whole list in a new memory but it doesn't touch the nested list objects. Instead it creates a reference of the original memory location for them. That is why when we change only the whole list the changes happen in only the new list not both. However, when we touch the nested list objects, changes happen in both the new and the old lists. So, this is `Shallow Copy`. 173 | 174 | > In case anyone wandering about `list.copy()` method, Yes, that is a shallow copy method too. 175 | 176 | *If you're still confused read this [answer](https://stackoverflow.com/questions/17246693/what-is-the-difference-between-shallow-copy-deepcopy-and-normal-assignment-oper) from stackoverflow.* 177 | 178 | #### Deep Copy 179 | 180 | > A deep copy creates a new object and recursively adds the copies of nested objects present in the original elements. 181 | 182 | A deepcopy solves the problem we had with the nested list with the shallow copy. Let's now apply deep copy method with the nested list example we just used earlier. 183 | 184 | ```py 185 | import copy 186 | 187 | old_list = [[1, 2, 3], [4, 5, 6]] 188 | new_list = copy.deepcopy(old_list) 189 | 190 | new_list[0][0] = "a" 191 | 192 | print(f"Old list: {old_list}") 193 | print(f"Old list memory location: {hex(id(old_list))}") 194 | print(f"New list: {new_list}") 195 | print(f"New list memory location: {hex(id(new_list))}") 196 | ``` 197 | Output: 198 | 199 | ```txt 200 | Old list: [[1, 2, 3], [4, 5, 6]] 201 | Old list memory location: 0x7fea699b4880 202 | New list: [['a', 2, 3], [4, 5, 6]] 203 | New list memory location: 0x7fea699b4600 204 | ``` 205 | 206 | So, using the `deepcopy()` we've solved the problem here. 207 | 208 | 209 | ***Something to remember :*** 210 | > Although in python we can change the array / list size anytime, however, in other programming languages such as C++ or Java, the size is fixed from the get go. So, in this course for learning purposes we'll always fix the size of the arrays / list from the get go too. It'll help us understand thigs more easily. For example, 211 | 212 | ```py 213 | >> arr = [0] * 10 214 | >> print(arr) 215 | [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 216 | ``` 217 | This will create an array of length 10. The value `0` indicate that the value of that index is empty. 218 | 219 | ### Array Traversal 220 | Array traversal is accessing the elements of an array one by one. (Basicly, `for loop`) 221 | 222 | In python3, 223 | ```py 224 | >> arr = [0,1,2,3,4,5] 225 | >> for i in arr: 226 | >> print(i, end=" ") 227 | 0 1 2 3 4 5 228 | ``` 229 | ### Reverse printing an Array 230 | We have an array and we need to print it's values in reverse order. 231 | 232 | ```py 233 | # with for loop 234 | def print_array_reverse(arr): 235 | for i in range(len(arr) - 1, -1, -1): 236 | print(arr[i], end=" ") 237 | 238 | # with while loop 239 | def print_array_reverse(arr): 240 | i = len(arr) - 1 241 | while i >= 0: 242 | print(arr[i], end=" ") 243 | i -= 1 244 | 245 | >> print_array_reverse([0,1,2,3,4,5]) 246 | 5 4 3 2 1 0 247 | ``` 248 | ### Resizing an Array 249 | 250 | ### Shifting an array Left 251 | ### Shifting an array Right 252 | ### Inserting an element into an Array 253 | We have an array for example, `arr = [1 ,20 ,5 ,78 ,30 ,0]` (Here, `0` means empty value). We need to insert a value for example, `100` in the `2`nd index. So that the resulting array will looks like, 254 | `arr = [1 ,20 ,200, 5, 78, 30]` 255 | 256 | So, we can achieve this by, 257 | * Shift all the values 1 index to right (we have some empty space to the right) 258 | * After shifting all the values to the right, index `2` will be empty. Simply, insert the value into index `2` 259 | 260 | ![Gif](https://media.giphy.com/media/aJg1xxk4TR3Csvp9St/giphy.gif) 261 | 262 | In python3, 263 | 264 | ```py 265 | def insert(arr, index, value, size): 266 | if size == len(arr): 267 | print("No space in array!") 268 | return 269 | 270 | if index < 0 or index > size: 271 | print("Wrong Index!") 272 | return 273 | 274 | else: 275 | for i in range(size, index - 1, -1): 276 | arr[i] = arr[i - 1] 277 | 278 | arr[index] = value 279 | print(arr) 280 | 281 | >> arr = [1, 20, 5, 78, 30, 0] 282 | >> insert(arr, 2, 100, 5)) 283 | [1, 20, 100, 5, 78, 30] 284 | ``` 285 | ### Removing an element from an array 286 | ### Rotating an array Left 287 | ### Rotating an array Right 288 | 289 | 290 | ### Rotate By K cell to right 291 | 292 | ```py 293 | def rightShift(source,k): 294 | 295 | i=len(source)-1 #pointer at the last index of source 296 | 297 | while(i>=k): 298 | 299 | source[i]=source[i-k] #shifting elements k places to the right 300 | 301 | i=i-1 302 | 303 | i=0 304 | 305 | while(i= self.countNode() or idx < 0: 71 | return None 72 | 73 | while tail != None: 74 | if idx == counter: 75 | return tail 76 | 77 | tail = tail.next 78 | counter += 1 79 | 80 | # returns the element of the Node at the given index. 81 | # For invalid idx return None. 82 | def get(self, idx): 83 | 84 | tail = self.head 85 | counter = 0 86 | 87 | # index validation 88 | if idx >= self.countNode() or idx < 0: 89 | return None 90 | 91 | while tail != None: 92 | if counter == idx: 93 | return tail.element 94 | 95 | tail = tail.next 96 | counter += 1 97 | 98 | # updates the element of the Node at the given index. 99 | # Returns the old element that was replaced. For invalid index return None. 100 | # parameter: index, element 101 | def set(self, idx, elem): 102 | 103 | tail = self.head 104 | counter = 0 105 | 106 | # index validation 107 | if idx >= self.countNode() or idx < 0: 108 | return None 109 | 110 | while tail != None: 111 | 112 | if counter == idx: 113 | oldElement = tail.element 114 | tail.element = elem 115 | 116 | return oldElement 117 | 118 | tail = tail.next 119 | counter += 1 120 | 121 | # returns the index of the Node containing the given element. 122 | # if the element does not exist in the List, return -1. 123 | def indexOf(self, elem): 124 | 125 | tail = self.head 126 | index = 0 127 | 128 | while tail != None: 129 | 130 | if tail.element == elem: 131 | return index 132 | 133 | tail = tail.next 134 | index += 1 135 | 136 | return -1 137 | 138 | # returns true if the element exists in the List, return false otherwise. 139 | def contains(self, elem): 140 | 141 | tail = self.head 142 | 143 | while tail != None: 144 | 145 | if tail.element == elem: 146 | return True 147 | 148 | tail = tail.next 149 | 150 | return False 151 | 152 | # Makes a duplicate copy of the given List. Returns the reference of the duplicate list. 153 | def copyList(self): 154 | 155 | newHead = None 156 | tail = self.head 157 | currentNode = None 158 | 159 | while tail != None: 160 | 161 | newNode = Node(tail.element, None) 162 | 163 | if newHead == None: 164 | newHead = newNode 165 | currentNode = newHead 166 | 167 | else: 168 | currentNode.next = newNode 169 | currentNode = newNode 170 | 171 | tail = tail.next 172 | 173 | return newHead 174 | 175 | # Makes a reversed copy of the given List. Returns the head reference of the reversed list. 176 | def reverseList(self): 177 | 178 | newHead = None 179 | nextNode = None 180 | tail = self.head 181 | 182 | while tail != None: 183 | 184 | nextNode = tail.next 185 | tail.next = newHead 186 | newHead = tail 187 | tail = nextNode 188 | 189 | return newHead 190 | 191 | # inserts Node containing the given element at the given index 192 | # Check validity of index. 193 | def insert(self, elem, idx): 194 | 195 | if idx >= self.countNode() + 1 or idx < 0: 196 | return None 197 | 198 | newNode = Node(elem, None) 199 | 200 | if idx == 0: 201 | newNode.next = self.head 202 | self.head = newNode 203 | 204 | else: 205 | 206 | pred = self.nodeAt(idx - 1) 207 | newNode.next = pred.next 208 | pred.next = newNode 209 | 210 | # removes Node at the given index. returns element of the removed node. 211 | # Check validity of index. return None if index is invalid. 212 | def remove(self, idx): 213 | 214 | if idx >= self.countNode() or idx < 0: 215 | return None 216 | 217 | if idx == 0: 218 | tmp = self.head 219 | removed = self.head.element 220 | self.head = self.head.next 221 | 222 | tmp.element = None 223 | tmp.next = None 224 | tmp = None 225 | 226 | else: 227 | current = self.head 228 | counter = 0 229 | while current != None: 230 | 231 | if counter == idx: 232 | pred = self.nodeAt(idx - 1) 233 | tmp = pred.next 234 | pred.next = tmp.next 235 | 236 | removed = tmp.element 237 | 238 | # Garbage Collection 239 | tmp.next = None 240 | tmp.element = None 241 | tmp = None 242 | 243 | current = current.next 244 | counter += 1 245 | 246 | return removed 247 | 248 | # Rotates the list to the left by 1 position. 249 | def rotateLeft(self): 250 | 251 | tail = self.head 252 | preHead = self.head 253 | head = self.head.next 254 | 255 | while tail != None: 256 | 257 | if tail.next == None: 258 | break 259 | 260 | tail = tail.next 261 | 262 | tail.next = self.head 263 | self.head = head 264 | preHead.next = None 265 | 266 | # Rotates the list to the right by 1 position. 267 | def rotateRight(self): 268 | 269 | p = self.head 270 | 271 | while p != None: 272 | 273 | if p.next == None: 274 | break 275 | 276 | prev = p 277 | p = p.next 278 | 279 | p.next = self.head 280 | self.head = prev.next 281 | prev.next = None 282 | 283 | 284 | print("////// Test 01 //////") 285 | a1 = [10, 20, 30, 40] 286 | h1 = LinkedList(a1) # Creates a linked list using the values from the array 287 | # head will refer to the Node that contains the element from a[0] 288 | 289 | 290 | h1.printList() # This should print: 10,20,30,40 291 | print(h1.countNode()) # This should print: 4 292 | 293 | print("////// Test 02 //////") 294 | # returns the reference of the Node at the given index. For invalid idx return None. 295 | myNode = h1.nodeAt(1) 296 | print( 297 | myNode.element 298 | ) # This should print: 20. In case of invalid index This will generate an Error. 299 | 300 | print("////// Test 03 //////") 301 | # returns the element of the Node at the given index. For invalid idx return None. 302 | val = h1.get(2) 303 | print(val) # This should print: 30. In case of invalid index This will print None. 304 | 305 | 306 | print("////// Test 04 //////") 307 | 308 | # updates the element of the Node at the given index. 309 | # Returns the old element that was replaced. For invalid index return None. 310 | # parameter: index, element 311 | 312 | print(h1.set(1, 85)) # This should print: 20 313 | h1.printList() # This should print: 10,85,30,40. 314 | print(h1.set(15, 85)) # This should print: None 315 | h1.printList() # This should print: 10,85,30,40. 316 | 317 | print("////// Test 05 //////") 318 | # returns the index of the Node containing the given element. 319 | # if the element does not exist in the List, return -1. 320 | index = h1.indexOf(40) 321 | print( 322 | index 323 | ) # This should print: 3. In case of element that doesn't exists in the list this will print -1. 324 | 325 | print("////// Test 06 //////") 326 | # returns true if the element exists in the List, return false otherwise. 327 | ask = h1.contains(40) 328 | print(ask) # This should print: True. 329 | 330 | 331 | print("////// Test 07 //////") 332 | a2 = [10, 20, 30, 40, 50, 60, 70] 333 | h2 = LinkedList(a2) # uses theconstructor where a is an built in list 334 | h2.printList() # This should print: 10,20,30,40,50,60,70. 335 | # Makes a duplicate copy of the given List. Returns the head reference of the duplicate list. 336 | copyH = h2.copyList() # Head node reference of the duplicate list 337 | h3 = LinkedList(copyH) # uses the constructor where a is head of a linkedlist 338 | h3.printList() # This should print: 10,20,30,40,50,60,70. 339 | 340 | print("////// Test 08 //////") 341 | a4 = [10, 20, 30, 40, 50] 342 | h4 = LinkedList(a4) # uses theconstructor where a is an built in list 343 | h4.printList() # This should print: 10,20,30,40,50. 344 | # Makes a reversed copy of the given List. Returns the head reference of the reversed list. 345 | revH = h4.reverseList() # Head node reference of the reversed list 346 | h5 = LinkedList(revH) # uses the constructor where a is head of a linkedlist 347 | h5.printList() # This should print: 50,40,30,20,10. 348 | 349 | print("////// Test 09 //////") 350 | a6 = [10, 20, 30, 40] 351 | h6 = LinkedList(a6) # uses theconstructor where a is an built in list 352 | h6.printList() # This should print: 10,20,30,40. 353 | 354 | # inserts Node containing the given element at the given index. Check validity of index. 355 | h6.insert(85, 0) 356 | h6.printList() # This should print: 85,10,20,30,40. 357 | h6.insert(95, 3) 358 | h6.printList() # This should print: 85,10,20,95,30,40. 359 | h6.insert(75, 6) 360 | h6.printList() # This should print: 85,10,20,95,30,40,75. 361 | 362 | 363 | print("////// Test 10 //////") 364 | a7 = [10, 20, 30, 40, 50, 60, 70] 365 | h7 = LinkedList(a7) # uses theconstructor where a is an built in list 366 | h7.printList() # This should print: 10,20,30,40,50,60,70. 367 | 368 | # removes Node at the given index. returns element of the removed node. 369 | # Check validity of index. return None if index is invalid. 370 | 371 | print("Removed element:", h7.remove(0)) # This should print: Removed element: 10 372 | h7.printList() # This should print: 20,30,40,50,60,70. 373 | print("Removed element: ", h7.remove(3)) # This should print: Removed element: 50 374 | h7.printList() # This should print: 20,30,40,60,70. 375 | print("Removed element: ", h7.remove(4)) # This should print: Removed element: 70 376 | h7.printList() # This should print: 20,30,40,60. 377 | 378 | 379 | print("////// Test 11 //////") 380 | a8 = [10, 20, 30, 40] 381 | h8 = LinkedList(a8) # uses theconstructor where a is an built in list 382 | h8.printList() # This should print: 10,20,30,40. 383 | 384 | # # Rotates the list to the left by 1 position. 385 | h8.rotateLeft() 386 | h8.printList() # This should print: 20,30,40,10. 387 | 388 | 389 | print("////// Test 12 //////") 390 | a9 = [10, 20, 30, 40] 391 | h9 = LinkedList(a9) # uses theconstructor where a is an built in list 392 | h9.printList() # This should print: 10,20,30,40. 393 | 394 | ## Rotates the list to the right by 1 position. 395 | h9.rotateRight() 396 | h9.printList() # This should print: 40,10,20,30. 397 | -------------------------------------------------------------------------------- /Lab Assignment Solutions/Fall 2022/Assignment 03/LinkedList2.py: -------------------------------------------------------------------------------- 1 | # ========Lab 03============ 2 | # Name: Mirza Mahrab Hossain Rudra 3 | # Student ID: 21101048 4 | # Section 15 5 | # ========================== 6 | 7 | 8 | class Node: 9 | def __init__(self, element, next): 10 | self.element = element 11 | self.next = next 12 | 13 | 14 | class LinkedList: 15 | def __init__(self, arr): 16 | # Design the constructor based on data type of a. If 'a' is built in python list then 17 | # Creates a linked list using the values from the given array. head will refer 18 | # to the Node that contains the element from a[0] 19 | # Else Sets the value of head. head will refer 20 | # to the given LinkedList 21 | 22 | newNode = Node(arr, None) 23 | 24 | # Hint: Use the type() function to determine the data type of a 25 | if type(arr) == Node: 26 | self.head = arr 27 | 28 | else: 29 | self.head = Node(arr[0], None) 30 | tail = self.head 31 | 32 | for i in range(1, len(arr)): 33 | 34 | newNode = Node(arr[i], None) 35 | tail.next = newNode 36 | tail = newNode 37 | 38 | # Count the number of nodes in the list 39 | def countNode(self): 40 | 41 | nodeCount = 0 42 | tail = self.head 43 | 44 | while tail != None: 45 | nodeCount += 1 46 | tail = tail.next 47 | 48 | return nodeCount 49 | 50 | # Print elements in the list 51 | def printList(self): 52 | 53 | tail = self.head 54 | 55 | while tail != None: 56 | 57 | if tail.next == None: 58 | print(tail.element) 59 | 60 | else: 61 | print(tail.element, end=" , ") 62 | 63 | tail = tail.next 64 | 65 | # returns the reference of the Node at the given index. For invalid index return None. 66 | def nodeAt(self, idx): 67 | 68 | tail = self.head 69 | counter = 0 70 | 71 | # index validation 72 | if idx >= self.countNode() or idx < 0: 73 | return None 74 | 75 | while tail != None: 76 | if idx == counter: 77 | return tail 78 | 79 | tail = tail.next 80 | counter += 1 81 | 82 | # returns the element of the Node at the given index. 83 | # For invalid idx return None. 84 | def get(self, idx): 85 | 86 | tail = self.head 87 | counter = 0 88 | 89 | # index validation 90 | if idx >= self.countNode() or idx < 0: 91 | return None 92 | 93 | while tail != None: 94 | if counter == idx: 95 | return tail.element 96 | 97 | tail = tail.next 98 | counter += 1 99 | 100 | # updates the element of the Node at the given index. 101 | # Returns the old element that was replaced. For invalid index return None. 102 | # parameter: index, element 103 | def set(self, idx, elem): 104 | 105 | tail = self.head 106 | counter = 0 107 | 108 | # index validation 109 | if idx >= self.countNode() or idx < 0: 110 | return None 111 | 112 | while tail != None: 113 | 114 | if counter == idx: 115 | oldElement = tail.element 116 | tail.element = elem 117 | 118 | return oldElement 119 | 120 | tail = tail.next 121 | counter += 1 122 | 123 | # returns the index of the Node containing the given element. 124 | # if the element does not exist in the List, return -1. 125 | def indexOf(self, elem): 126 | 127 | tail = self.head 128 | index = 0 129 | 130 | while tail != None: 131 | 132 | if tail.element == elem: 133 | return index 134 | 135 | tail = tail.next 136 | index += 1 137 | 138 | return -1 139 | 140 | # returns true if the element exists in the List, return false otherwise. 141 | def contains(self, elem): 142 | 143 | tail = self.head 144 | 145 | while tail != None: 146 | 147 | if tail.element == elem: 148 | return True 149 | 150 | tail = tail.next 151 | 152 | return False 153 | 154 | # Makes a duplicate copy of the given List. Returns the reference of the duplicate list. 155 | def copyList(self): 156 | 157 | newHead = None 158 | tail = self.head 159 | currentNode = None 160 | 161 | while tail != None: 162 | 163 | newNode = Node(tail.element, None) 164 | 165 | if newHead == None: 166 | newHead = newNode 167 | currentNode = newHead 168 | 169 | else: 170 | currentNode.next = newNode 171 | currentNode = newNode 172 | 173 | tail = tail.next 174 | 175 | return newHead 176 | 177 | # Makes a reversed copy of the given List. Returns the head reference of the reversed list. 178 | def reverseList(self): 179 | 180 | newHead = None 181 | nextNode = None 182 | tail = self.head 183 | 184 | while tail != None: 185 | 186 | nextNode = tail.next 187 | tail.next = newHead 188 | newHead = tail 189 | tail = nextNode 190 | 191 | return newHead 192 | 193 | # inserts Node containing the given element at the given index 194 | # Check validity of index. 195 | def insert(self, elem, idx): 196 | 197 | if idx >= self.countNode() + 1 or idx < 0: 198 | return None 199 | 200 | newNode = Node(elem, None) 201 | 202 | if idx == 0: 203 | newNode.next = self.head 204 | self.head = newNode 205 | 206 | else: 207 | 208 | pred = self.nodeAt(idx - 1) 209 | newNode.next = pred.next 210 | pred.next = newNode 211 | 212 | # removes Node at the given index. returns element of the removed node. 213 | # Check validity of index. return None if index is invalid. 214 | def remove(self, idx): 215 | 216 | if idx >= self.countNode() or idx < 0: 217 | return None 218 | 219 | if idx == 0: 220 | tmp = self.head 221 | removed = self.head.element 222 | self.head = self.head.next 223 | 224 | tmp.element = None 225 | tmp.next = None 226 | tmp = None 227 | 228 | else: 229 | current = self.head 230 | counter = 0 231 | while current != None: 232 | 233 | if counter == idx: 234 | pred = self.nodeAt(idx - 1) 235 | tmp = pred.next 236 | pred.next = tmp.next 237 | 238 | removed = tmp.element 239 | 240 | # Garbage Collection 241 | tmp.next = None 242 | tmp.element = None 243 | tmp = None 244 | 245 | current = current.next 246 | counter += 1 247 | 248 | return removed 249 | 250 | # Rotates the list to the left by 1 position. 251 | def rotateLeft(self): 252 | 253 | tail = self.head 254 | preHead = self.head 255 | head = self.head.next 256 | 257 | while tail != None: 258 | 259 | if tail.next == None: 260 | break 261 | 262 | tail = tail.next 263 | 264 | tail.next = self.head 265 | self.head = head 266 | preHead.next = None 267 | 268 | # Rotates the list to the right by 1 position. 269 | def rotateRight(self): 270 | 271 | p = self.head 272 | 273 | while p != None: 274 | 275 | if p.next == None: 276 | break 277 | 278 | prev = p 279 | p = p.next 280 | 281 | p.next = self.head 282 | self.head = prev.next 283 | prev.next = None 284 | 285 | 286 | print("////// Test 01 //////") 287 | a1 = Node(10, None) 288 | # a1 = [10, 20, 30, 40] 289 | h1 = LinkedList(a1) # Creates a linked list using the values from the array 290 | # head will refer to the Node that contains the element from a[0] 291 | 292 | 293 | h1.printList() # This should print: 10,20,30,40 294 | print(h1.countNode()) # This should print: 4 295 | 296 | print("////// Test 02 //////") 297 | # returns the reference of the Node at the given index. For invalid idx return None. 298 | myNode = h1.nodeAt(1) 299 | print( 300 | myNode.element 301 | ) # This should print: 20. In case of invalid index This will generate an Error. 302 | 303 | print("////// Test 03 //////") 304 | # returns the element of the Node at the given index. For invalid idx return None. 305 | val = h1.get(2) 306 | print(val) # This should print: 30. In case of invalid index This will print None. 307 | 308 | 309 | print("////// Test 04 //////") 310 | 311 | # updates the element of the Node at the given index. 312 | # Returns the old element that was replaced. For invalid index return None. 313 | # parameter: index, element 314 | 315 | print(h1.set(1, 85)) # This should print: 20 316 | h1.printList() # This should print: 10,85,30,40. 317 | print(h1.set(15, 85)) # This should print: None 318 | h1.printList() # This should print: 10,85,30,40. 319 | 320 | print("////// Test 05 //////") 321 | # returns the index of the Node containing the given element. 322 | # if the element does not exist in the List, return -1. 323 | index = h1.indexOf(40) 324 | print( 325 | index 326 | ) # This should print: 3. In case of element that doesn't exists in the list this will print -1. 327 | 328 | print("////// Test 06 //////") 329 | # returns true if the element exists in the List, return false otherwise. 330 | ask = h1.contains(40) 331 | print(ask) # This should print: True. 332 | 333 | 334 | print("////// Test 07 //////") 335 | a2 = [10, 20, 30, 40, 50, 60, 70] 336 | h2 = LinkedList(a2) # uses theconstructor where a is an built in list 337 | h2.printList() # This should print: 10,20,30,40,50,60,70. 338 | # Makes a duplicate copy of the given List. Returns the head reference of the duplicate list. 339 | copyH = h2.copyList() # Head node reference of the duplicate list 340 | h3 = LinkedList(copyH) # uses the constructor where a is head of a linkedlist 341 | h3.printList() # This should print: 10,20,30,40,50,60,70. 342 | 343 | print("////// Test 08 //////") 344 | a4 = [10, 20, 30, 40, 50] 345 | h4 = LinkedList(a4) # uses theconstructor where a is an built in list 346 | h4.printList() # This should print: 10,20,30,40,50. 347 | # Makes a reversed copy of the given List. Returns the head reference of the reversed list. 348 | revH = h4.reverseList() # Head node reference of the reversed list 349 | h5 = LinkedList(revH) # uses the constructor where a is head of a linkedlist 350 | h5.printList() # This should print: 50,40,30,20,10. 351 | 352 | print("////// Test 09 //////") 353 | a6 = [10, 20, 30, 40] 354 | h6 = LinkedList(a6) # uses theconstructor where a is an built in list 355 | h6.printList() # This should print: 10,20,30,40. 356 | 357 | # inserts Node containing the given element at the given index. Check validity of index. 358 | h6.insert(85, 0) 359 | h6.printList() # This should print: 85,10,20,30,40. 360 | h6.insert(95, 3) 361 | h6.printList() # This should print: 85,10,20,95,30,40. 362 | h6.insert(75, 6) 363 | h6.printList() # This should print: 85,10,20,95,30,40,75. 364 | 365 | 366 | print("////// Test 10 //////") 367 | a7 = [10, 20, 30, 40, 50, 60, 70] 368 | h7 = LinkedList(a7) # uses theconstructor where a is an built in list 369 | h7.printList() # This should print: 10,20,30,40,50,60,70. 370 | 371 | # removes Node at the given index. returns element of the removed node. 372 | # Check validity of index. return None if index is invalid. 373 | 374 | print("Removed element:", h7.remove(0)) # This should print: Removed element: 10 375 | h7.printList() # This should print: 20,30,40,50,60,70. 376 | print("Removed element: ", h7.remove(3)) # This should print: Removed element: 50 377 | h7.printList() # This should print: 20,30,40,60,70. 378 | print("Removed element: ", h7.remove(4)) # This should print: Removed element: 70 379 | h7.printList() # This should print: 20,30,40,60. 380 | 381 | 382 | print("////// Test 11 //////") 383 | a8 = [10, 20, 30, 40] 384 | h8 = LinkedList(a8) # uses theconstructor where a is an built in list 385 | h8.printList() # This should print: 10,20,30,40. 386 | 387 | # # Rotates the list to the left by 1 position. 388 | h8.rotateLeft() 389 | h8.printList() # This should print: 20,30,40,10. 390 | 391 | 392 | print("////// Test 12 //////") 393 | a9 = [10, 20, 30, 40] 394 | h9 = LinkedList(a9) # uses theconstructor where a is an built in list 395 | h9.printList() # This should print: 10,20,30,40. 396 | 397 | ## Rotates the list to the right by 1 position. 398 | h9.rotateRight() 399 | h9.printList() # This should print: 40,10,20,30. 400 | -------------------------------------------------------------------------------- /Lab Assignment Solutions/Spring 2022/Assignment 01/CSE220 Lab Assignment 01.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# CSE220 Lab Assignment 01" 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "### Name : Mirza Meherab Hosen Rudra\n", 15 | "### ID : 21101048" 16 | ] 17 | }, 18 | { 19 | "cell_type": "markdown", 20 | "metadata": {}, 21 | "source": [ 22 | "## Linear Arrays" 23 | ] 24 | }, 25 | { 26 | "cell_type": "code", 27 | "execution_count": 1, 28 | "metadata": {}, 29 | "outputs": [ 30 | { 31 | "name": "stdout", 32 | "output_type": "stream", 33 | "text": [ 34 | "[40, 50, 60, 0, 0, 0]\n" 35 | ] 36 | } 37 | ], 38 | "source": [ 39 | "# Linear Arrays\n", 40 | "# Probem -01\n", 41 | "\n", 42 | "\n", 43 | "def shiftLeft(arr, k):\n", 44 | "\n", 45 | " for i in range(len(arr)):\n", 46 | " if i < len(arr) - k and k > 0:\n", 47 | " arr[i] = arr[i + k]\n", 48 | "\n", 49 | " else:\n", 50 | " if k <= 0:\n", 51 | " print(\"Invalid 'k' Position\")\n", 52 | " return\n", 53 | "\n", 54 | " else:\n", 55 | " arr[i] = 0\n", 56 | "\n", 57 | " print(arr)\n", 58 | "\n", 59 | "\n", 60 | "def main():\n", 61 | " source = [10, 20, 30, 40, 50, 60]\n", 62 | " shiftLeft(source, 3)\n", 63 | "\n", 64 | "\n", 65 | "if __name__ == \"__main__\":\n", 66 | " main()\n" 67 | ] 68 | }, 69 | { 70 | "cell_type": "code", 71 | "execution_count": 2, 72 | "metadata": {}, 73 | "outputs": [ 74 | { 75 | "name": "stdout", 76 | "output_type": "stream", 77 | "text": [ 78 | "[40, 50, 60, 10, 20, 30]\n" 79 | ] 80 | } 81 | ], 82 | "source": [ 83 | "# Problem -02\n", 84 | "\n", 85 | "\n", 86 | "def rotateLeft(arr, k):\n", 87 | "\n", 88 | " temp = [value for value in arr[:k]]\n", 89 | "\n", 90 | " for i in range(len(arr)):\n", 91 | " if i < len(arr) - k and k > 0:\n", 92 | " arr[i] = arr[i + k]\n", 93 | "\n", 94 | " else:\n", 95 | " if k <= 0 or k > len(arr):\n", 96 | " print(\"Invalid 'k' position\")\n", 97 | " return\n", 98 | " else:\n", 99 | " arr[i] = temp[i - (len(arr) - k)]\n", 100 | "\n", 101 | " print(arr)\n", 102 | "\n", 103 | "\n", 104 | "def main():\n", 105 | " source = [10, 20, 30, 40, 50, 60]\n", 106 | " rotateLeft(source, 3)\n", 107 | "\n", 108 | "\n", 109 | "if __name__ == \"__main__\":\n", 110 | " main()\n" 111 | ] 112 | }, 113 | { 114 | "cell_type": "code", 115 | "execution_count": 3, 116 | "metadata": {}, 117 | "outputs": [ 118 | { 119 | "name": "stdout", 120 | "output_type": "stream", 121 | "text": [ 122 | "[10, 20, 40, 50, 0, 0, 0]\n" 123 | ] 124 | } 125 | ], 126 | "source": [ 127 | "# Problem -03\n", 128 | "\n", 129 | "\n", 130 | "def remove(arr, size, index):\n", 131 | "\n", 132 | " if index < 0 or index > size:\n", 133 | " print(\"Invalid Index\")\n", 134 | " return\n", 135 | "\n", 136 | " for i in range(size):\n", 137 | " if i >= index and i <= size - 1:\n", 138 | " arr[i] = arr[i + 1]\n", 139 | "\n", 140 | " arr[size - 1] = 0\n", 141 | "\n", 142 | " print(arr)\n", 143 | "\n", 144 | "\n", 145 | "def main():\n", 146 | " source = [10, 20, 30, 40, 50, 0, 0]\n", 147 | " remove(source, 5, 2)\n", 148 | "\n", 149 | "\n", 150 | "if __name__ == \"__main__\":\n", 151 | " main()\n" 152 | ] 153 | }, 154 | { 155 | "cell_type": "code", 156 | "execution_count": 4, 157 | "metadata": {}, 158 | "outputs": [ 159 | { 160 | "name": "stdout", 161 | "output_type": "stream", 162 | "text": [ 163 | "[10, 30, 50, 0, 0, 0, 0, 0, 0]\n" 164 | ] 165 | } 166 | ], 167 | "source": [ 168 | "# Problem -04\n", 169 | "\n", 170 | "\n", 171 | "def removeAll(arr, size, element):\n", 172 | " if size <= 0 and size > len(arr):\n", 173 | " print(\"Invalid Size\")\n", 174 | " return\n", 175 | "\n", 176 | " # If index item is equal to the element to remove\n", 177 | " # replace that index item as 0\n", 178 | " for i in range(size):\n", 179 | " if arr[i] == element:\n", 180 | " arr[i] = 0\n", 181 | "\n", 182 | " j = 0\n", 183 | " for i in range(size):\n", 184 | " # If index item is not 0 (after converting\n", 185 | " # all target elements to 0)\n", 186 | " # Make the array compact with the non zero items\n", 187 | " if arr[i] != 0:\n", 188 | " temp = arr[j]\n", 189 | " arr[j] = arr[i]\n", 190 | " arr[i] = temp\n", 191 | " j += 1\n", 192 | "\n", 193 | " print(arr)\n", 194 | "\n", 195 | "\n", 196 | "def main():\n", 197 | " source = [10, 2, 30, 2, 50, 2, 2, 0, 0]\n", 198 | " removeAll(source, 7, 2)\n", 199 | "\n", 200 | "\n", 201 | "if __name__ == \"__main__\":\n", 202 | " main()\n" 203 | ] 204 | }, 205 | { 206 | "cell_type": "code", 207 | "execution_count": 5, 208 | "metadata": {}, 209 | "outputs": [ 210 | { 211 | "name": "stdout", 212 | "output_type": "stream", 213 | "text": [ 214 | "True\n", 215 | "False\n", 216 | "True\n" 217 | ] 218 | } 219 | ], 220 | "source": [ 221 | "# Problem -05\n", 222 | "\n", 223 | "\n", 224 | "def Splitting_array(arr):\n", 225 | " arr_A = [0]\n", 226 | " arr_B = []\n", 227 | " flag = None\n", 228 | "\n", 229 | " for i in range(len(arr)):\n", 230 | " if i == 0:\n", 231 | " arr_A[i] = arr[i]\n", 232 | " arr_B = arr[i + 1 : (len(arr))]\n", 233 | " if sum(arr_A) == sum(arr_B):\n", 234 | " flag = True\n", 235 | " break\n", 236 | " else:\n", 237 | " arr_A = []\n", 238 | " flag = False\n", 239 | " else:\n", 240 | " arr_A = arr[0 : i + 1]\n", 241 | " arr_B = arr[i + 1 : (len(arr))]\n", 242 | " if sum(arr_A) == sum(arr_B):\n", 243 | " flag = True\n", 244 | " break\n", 245 | " else:\n", 246 | " flag = False\n", 247 | " print(flag)\n", 248 | "\n", 249 | "\n", 250 | "def main():\n", 251 | " arr = [1, 1, 1, 2, 1]\n", 252 | " Splitting_array(arr)\n", 253 | "\n", 254 | " arr = [2, 1, 1, 2, 1]\n", 255 | " Splitting_array(arr)\n", 256 | "\n", 257 | " arr = [10, 3, 1, 2, 10]\n", 258 | " Splitting_array(arr)\n", 259 | "\n", 260 | "\n", 261 | "if __name__ == \"__main__\":\n", 262 | " main()\n" 263 | ] 264 | }, 265 | { 266 | "cell_type": "code", 267 | "execution_count": 6, 268 | "metadata": {}, 269 | "outputs": [ 270 | { 271 | "name": "stdout", 272 | "output_type": "stream", 273 | "text": [ 274 | "n = 2: [0, 1, 2, 1]\n", 275 | "n = 3: [0, 0, 1, 0, 2, 1, 3, 2, 1]\n", 276 | "n = 4: [0, 0, 0, 1, 0, 0, 2, 1, 0, 3, 2, 1, 4, 3, 2, 1]\n" 277 | ] 278 | } 279 | ], 280 | "source": [ 281 | "# Problem -06\n", 282 | "\n", 283 | "\n", 284 | "def array_series(num) -> list:\n", 285 | "\n", 286 | " arr = [0] * (num * num)\n", 287 | "\n", 288 | " i = 1\n", 289 | " while i <= num:\n", 290 | " j = 1\n", 291 | " while j <= i:\n", 292 | " arr[(i * num) - j] = j\n", 293 | "\n", 294 | " j += 1\n", 295 | " i += 1\n", 296 | "\n", 297 | " return arr\n", 298 | "\n", 299 | "\n", 300 | "def main():\n", 301 | "\n", 302 | " # Uncomment for manual input\n", 303 | " # print(array_series(int(input(\"Input 'n' = \"))))\n", 304 | "\n", 305 | " print(f\"n = 2: {array_series(2)}\")\n", 306 | " print(f\"n = 3: {array_series(3)}\")\n", 307 | " print(f\"n = 4: {array_series(4)}\")\n", 308 | "\n", 309 | "\n", 310 | "if __name__ == \"__main__\":\n", 311 | " main()\n" 312 | ] 313 | }, 314 | { 315 | "cell_type": "code", 316 | "execution_count": 7, 317 | "metadata": {}, 318 | "outputs": [ 319 | { 320 | "name": "stdout", 321 | "output_type": "stream", 322 | "text": [ 323 | "3\n", 324 | "4\n" 325 | ] 326 | } 327 | ], 328 | "source": [ 329 | "# Problem -07\n", 330 | "\n", 331 | "\n", 332 | "def maxBunch(arr) -> None:\n", 333 | "\n", 334 | " streak, currnt_streak = 1, 1\n", 335 | " for i in range(len(arr)):\n", 336 | " # if this is the last element, print the result\n", 337 | " if i == len(arr) - 1:\n", 338 | " print(streak)\n", 339 | " return\n", 340 | "\n", 341 | " elif arr[i] == arr[i + 1]:\n", 342 | " currnt_streak += 1\n", 343 | " else:\n", 344 | " currnt_streak = 1\n", 345 | "\n", 346 | " # if current streak is higher than previous streaks\n", 347 | " # make this the new current streak\n", 348 | " if currnt_streak >= streak:\n", 349 | " streak = currnt_streak\n", 350 | "\n", 351 | "\n", 352 | "def main():\n", 353 | " source = [1, 2, 2, 3, 4, 4, 4]\n", 354 | " maxBunch(source)\n", 355 | "\n", 356 | " source = [1, 1, 2, 2, 1, 1, 1, 1]\n", 357 | " maxBunch(source)\n", 358 | "\n", 359 | "\n", 360 | "if __name__ == \"__main__\":\n", 361 | " main()\n" 362 | ] 363 | }, 364 | { 365 | "cell_type": "code", 366 | "execution_count": 8, 367 | "metadata": {}, 368 | "outputs": [ 369 | { 370 | "name": "stdout", 371 | "output_type": "stream", 372 | "text": [ 373 | "True\n", 374 | "False\n" 375 | ] 376 | } 377 | ], 378 | "source": [ 379 | "# Problem -08\n", 380 | "\n", 381 | "\n", 382 | "def repetition(arr) -> bool:\n", 383 | "\n", 384 | " repeated_values = []\n", 385 | " # Create a dictionary for counting item repetition\n", 386 | " dictionary = {item: arr.count(item) for item in arr}\n", 387 | "\n", 388 | " # if item repetition value is more than 1,\n", 389 | " # item has been repeated so add to a list for more experiment\n", 390 | " for repeated_count in dictionary.values():\n", 391 | " if repeated_count > 1:\n", 392 | " repeated_values.append(repeated_count)\n", 393 | "\n", 394 | " # if 2 or more value are the same, length of set would be\n", 395 | " # smaller than the main list meaing there're same repeated value\n", 396 | " # for 2 or more items\n", 397 | " if len(repeated_values) == len(set(repeated_values)):\n", 398 | " return False\n", 399 | " else:\n", 400 | " return True\n", 401 | "\n", 402 | "\n", 403 | "def main():\n", 404 | " source = [4, 5, 6, 6, 4, 3, 6, 4]\n", 405 | " print(repetition(source))\n", 406 | "\n", 407 | " source = [3, 4, 6, 3, 4, 7, 4, 6, 8, 6, 6]\n", 408 | " print(repetition(source))\n", 409 | "\n", 410 | "\n", 411 | "if __name__ == \"__main__\":\n", 412 | " main()\n" 413 | ] 414 | }, 415 | { 416 | "cell_type": "markdown", 417 | "metadata": {}, 418 | "source": [ 419 | "## Circular Array" 420 | ] 421 | }, 422 | { 423 | "cell_type": "code", 424 | "execution_count": 9, 425 | "metadata": {}, 426 | "outputs": [ 427 | { 428 | "name": "stdout", 429 | "output_type": "stream", 430 | "text": [ 431 | "True\n", 432 | "False\n" 433 | ] 434 | } 435 | ], 436 | "source": [ 437 | "# Circular array\n", 438 | "# Problem -01\n", 439 | "\n", 440 | "\n", 441 | "def is_palindrome(arr, start, size) -> bool:\n", 442 | " new_arr = []\n", 443 | "\n", 444 | " for _ in range(size):\n", 445 | " if arr[start] != 0:\n", 446 | " new_arr.append(arr[start])\n", 447 | " start += 1\n", 448 | " if start == len(arr):\n", 449 | " start = 0\n", 450 | "\n", 451 | " arr_half = (len(new_arr) + 1) // 2\n", 452 | "\n", 453 | " if new_arr[0:arr_half] == new_arr[-1 : -(arr_half + 1) : -1]:\n", 454 | " return True\n", 455 | " else:\n", 456 | " return False\n", 457 | "\n", 458 | "\n", 459 | "def main():\n", 460 | " source = [20, 10, 0, 0, 0, 10, 20, 30]\n", 461 | " print(is_palindrome(source, start=5, size=5))\n", 462 | "\n", 463 | " source = [10, 20, 0, 0, 0, 10, 20, 30]\n", 464 | " print(is_palindrome(source, start=5, size=5))\n", 465 | "\n", 466 | "\n", 467 | "if __name__ == \"__main__\":\n", 468 | " main()\n" 469 | ] 470 | }, 471 | { 472 | "cell_type": "code", 473 | "execution_count": 10, 474 | "metadata": {}, 475 | "outputs": [ 476 | { 477 | "name": "stdout", 478 | "output_type": "stream", 479 | "text": [ 480 | "[10, 20, 40]\n" 481 | ] 482 | } 483 | ], 484 | "source": [ 485 | "# Problem -02\n", 486 | "\n", 487 | "\n", 488 | "def intersection(array_1, start_1, size_1, array_2, start_2, size_2):\n", 489 | "\n", 490 | " intersection_array = []\n", 491 | "\n", 492 | " # Array 1\n", 493 | " array_1_A = []\n", 494 | " array_1_B = []\n", 495 | " for i in range(1, len(array_1)):\n", 496 | " if array_1[i] == 0 and array_1[i - 1] != 0:\n", 497 | " for j in range(i):\n", 498 | " array_1_B.append(array_1[j])\n", 499 | "\n", 500 | " for i in range(1, len(array_1)):\n", 501 | " if array_1[i] != 0 and array_1[i - 1] == 0:\n", 502 | " for j in range(i, len(array_1)):\n", 503 | " array_1_A.append(array_1[j])\n", 504 | "\n", 505 | " # Array 2\n", 506 | " array_2_A = []\n", 507 | " array_2_B = []\n", 508 | " for i in range(1, len(array_2)):\n", 509 | " if array_2[i] == 0 and array_2[i - 1] != 0:\n", 510 | " for j in range(i):\n", 511 | " array_2_B.append(array_2[j])\n", 512 | "\n", 513 | " for i in range(1, len(array_2)):\n", 514 | " if array_2[i] != 0 and array_2[i - 1] == 0:\n", 515 | " for j in range(i, len(array_2)):\n", 516 | " array_2_A.append(array_2[j])\n", 517 | "\n", 518 | " # Combine\n", 519 | " new_array_1 = array_1_A + array_1_B\n", 520 | " new_array_2 = array_2_A + array_2_B\n", 521 | "\n", 522 | " # search for common items\n", 523 | " for i in range(len(new_array_1)):\n", 524 | " new = new_array_1[i]\n", 525 | " for i in range(len(new_array_2)):\n", 526 | " if new == new_array_2[i]:\n", 527 | " if new not in intersection_array:\n", 528 | " intersection_array.append(new)\n", 529 | " else:\n", 530 | " continue\n", 531 | " else:\n", 532 | " continue\n", 533 | "\n", 534 | " print(intersection_array)\n", 535 | "\n", 536 | "\n", 537 | "def main():\n", 538 | " array_1 = [40, 50, 0, 0, 0, 10, 20, 30]\n", 539 | " array_2 = [10, 20, 5, 0, 0, 0, 0, 0, 5, 40, 15, 25]\n", 540 | "\n", 541 | " intersection(array_1, 5, 5, array_2, 8, 7)\n", 542 | "\n", 543 | "\n", 544 | "if __name__ == \"__main__\":\n", 545 | " main()\n" 546 | ] 547 | }, 548 | { 549 | "cell_type": "code", 550 | "execution_count": 11, 551 | "metadata": {}, 552 | "outputs": [ 553 | { 554 | "name": "stdout", 555 | "output_type": "stream", 556 | "text": [ 557 | "Current Players: ['Guts', 'Eren', 'Kaneki', 'Araragi', 'Hachiman', 'Itachi', 'Lelouch']\n", 558 | "Current Players: ['Lelouch', 'Guts', 'Eren', 'Kaneki', 'Araragi', 'Hachiman', 'Itachi']\n", 559 | "Current Players: ['Itachi', 'Lelouch', 'Guts', 'Eren', 'Kaneki', 'Araragi', 'Hachiman']\n", 560 | "Current Players: ['Hachiman', 'Itachi', 'Lelouch', 'Guts', 'Eren', 'Kaneki', 'Araragi']\n", 561 | "Current Players: ['Araragi', 'Hachiman', 'Itachi', 'Lelouch', 'Guts', 'Eren', 'Kaneki']\n", 562 | "\n", 563 | "The music stopped!!!\n", 564 | "Player Name: Lelouch in Position: 3 is out of the Game!\n", 565 | "\n", 566 | "Current Players: ['Kaneki', 'Araragi', 'Hachiman', 'Itachi', 'Guts', 'Eren']\n", 567 | "\n", 568 | "The music stopped!!!\n", 569 | "Player Name: Itachi in Position: 3 is out of the Game!\n", 570 | "\n", 571 | "Current Players: ['Eren', 'Kaneki', 'Araragi', 'Hachiman', 'Guts']\n", 572 | "Current Players: ['Guts', 'Eren', 'Kaneki', 'Araragi', 'Hachiman']\n", 573 | "Current Players: ['Hachiman', 'Guts', 'Eren', 'Kaneki', 'Araragi']\n", 574 | "Current Players: ['Araragi', 'Hachiman', 'Guts', 'Eren', 'Kaneki']\n", 575 | "Current Players: ['Kaneki', 'Araragi', 'Hachiman', 'Guts', 'Eren']\n", 576 | "Current Players: ['Eren', 'Kaneki', 'Araragi', 'Hachiman', 'Guts']\n", 577 | "Current Players: ['Guts', 'Eren', 'Kaneki', 'Araragi', 'Hachiman']\n", 578 | "Current Players: ['Hachiman', 'Guts', 'Eren', 'Kaneki', 'Araragi']\n", 579 | "Current Players: ['Araragi', 'Hachiman', 'Guts', 'Eren', 'Kaneki']\n", 580 | "Current Players: ['Kaneki', 'Araragi', 'Hachiman', 'Guts', 'Eren']\n", 581 | "\n", 582 | "The music stopped!!!\n", 583 | "Player Name: Hachiman in Position: 2 is out of the Game!\n", 584 | "\n", 585 | "Current Players: ['Eren', 'Kaneki', 'Araragi', 'Guts']\n", 586 | "Current Players: ['Guts', 'Eren', 'Kaneki', 'Araragi']\n", 587 | "Current Players: ['Araragi', 'Guts', 'Eren', 'Kaneki']\n", 588 | "Current Players: ['Kaneki', 'Araragi', 'Guts', 'Eren']\n", 589 | "Current Players: ['Eren', 'Kaneki', 'Araragi', 'Guts']\n", 590 | "\n", 591 | "The music stopped!!!\n", 592 | "Player Name: Araragi in Position: 2 is out of the Game!\n", 593 | "\n", 594 | "Current Players: ['Guts', 'Eren', 'Kaneki']\n", 595 | "Current Players: ['Kaneki', 'Guts', 'Eren']\n", 596 | "\n", 597 | "The music stopped!!!\n", 598 | "Player Name: Guts in Position: 1 is out of the Game!\n", 599 | "\n", 600 | "Current Players: ['Eren', 'Kaneki']\n", 601 | "Current Players: ['Kaneki', 'Eren']\n", 602 | "Current Players: ['Eren', 'Kaneki']\n", 603 | "Current Players: ['Kaneki', 'Eren']\n", 604 | "Current Players: ['Eren', 'Kaneki']\n", 605 | "Current Players: ['Kaneki', 'Eren']\n", 606 | "Current Players: ['Eren', 'Kaneki']\n", 607 | "Current Players: ['Kaneki', 'Eren']\n", 608 | "\n", 609 | "The music stopped!!!\n", 610 | "Player Name: Eren in Position: 1 is out of the Game!\n", 611 | "\n", 612 | "We've got the Winner!!!\n", 613 | "Aaand the winner is: Kaneki\n" 614 | ] 615 | } 616 | ], 617 | "source": [ 618 | "# Problem -03\n", 619 | "\n", 620 | "import random\n", 621 | "\n", 622 | "\n", 623 | "def musical_chair(players):\n", 624 | " player_num = len(players)\n", 625 | "\n", 626 | " while player_num > 1:\n", 627 | "\n", 628 | " print(f\"Current Players: {players}\")\n", 629 | " var = random.randint(0, 3)\n", 630 | "\n", 631 | " if var == 1:\n", 632 | " position = int(player_num / 2)\n", 633 | " print(\n", 634 | " f\"\\nThe music stopped!!!\\nPlayer Name: {players[position]} in Position: {position} is out of the Game!\\n\"\n", 635 | " )\n", 636 | " players.pop(position)\n", 637 | "\n", 638 | " # Circulate items\n", 639 | " players.insert(0, players[len(players) - 1])\n", 640 | " players.pop(len(players) - 1)\n", 641 | " player_num = len(players)\n", 642 | " print(f\"We've got the Winner!!!\\nAaand the winner is: {players[0]}\")\n", 643 | "\n", 644 | "\n", 645 | "def main():\n", 646 | " players = [\"Guts\", \"Eren\", \"Kaneki\", \"Araragi\", \"Hachiman\", \"Itachi\", \"Lelouch\"]\n", 647 | " musical_chair(players)\n", 648 | "\n", 649 | "\n", 650 | "if __name__ == \"__main__\":\n", 651 | " main()\n" 652 | ] 653 | } 654 | ], 655 | "metadata": { 656 | "interpreter": { 657 | "hash": "31f2aee4e71d21fbe5cf8b01ff0e069b9275f58929596ceb00d14d90e3e16cd6" 658 | }, 659 | "kernelspec": { 660 | "display_name": "Python 3.8.10 64-bit", 661 | "language": "python", 662 | "name": "python3" 663 | }, 664 | "language_info": { 665 | "codemirror_mode": { 666 | "name": "ipython", 667 | "version": 3 668 | }, 669 | "file_extension": ".py", 670 | "mimetype": "text/x-python", 671 | "name": "python", 672 | "nbconvert_exporter": "python", 673 | "pygments_lexer": "ipython3", 674 | "version": "3.8.10" 675 | }, 676 | "orig_nbformat": 4 677 | }, 678 | "nbformat": 4, 679 | "nbformat_minor": 2 680 | } 681 | --------------------------------------------------------------------------------