├── BFSingraph.py ├── BSTimplementation.py ├── DFSingraph.py ├── Dijkstrasalgorithm.py ├── Hashtableusage.py ├── Knapsackproblem.py ├── Linkedlistimplementation.py ├── README.md ├── armstrong.py ├── binarysearch.py ├── bubblesort.py ├── factorial.py ├── fibonacci_series.py ├── gcd.py ├── insert_into_bst.py ├── insertionsort.py ├── linearsearch.py ├── maximumofthree.py ├── mergesort.py ├── palindrome.py ├── perfect_number.py ├── prime_number.py ├── queue.py ├── quicksort.py ├── searching_in_bst.py ├── selectionsort.py ├── stack.py ├── string_anagram.py └── trianglepattern.py /BFSingraph.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | def bfs(graph, start_node): 4 | visited = set() 5 | queue = deque([start_node]) 6 | 7 | while queue: 8 | node = queue.popleft() 9 | if node not in visited: 10 | print(node, end=' ') 11 | visited.add(node) 12 | queue.extend(neighbor for neighbor in graph[node] if neighbor not in visited) 13 | -------------------------------------------------------------------------------- /BSTimplementation.py: -------------------------------------------------------------------------------- 1 | class TreeNode: 2 | def __init__(self, key): 3 | self.left = None 4 | self.right = None 5 | self.val = key 6 | 7 | def insert(root, key): 8 | if root is None: 9 | return TreeNode(key) 10 | if key < root.val: 11 | root.left = insert(root.left, key) 12 | else: 13 | root.right = insert(root.right, key) 14 | return root 15 | 16 | def search(root, key): 17 | if root is None or root.val == key: 18 | return root 19 | if root.val < key: 20 | return search(root.right, key) 21 | return search(root.left, key) 22 | -------------------------------------------------------------------------------- /DFSingraph.py: -------------------------------------------------------------------------------- 1 | def dfs(graph, node, visited): 2 | if node not in visited: 3 | print(node, end=' ') 4 | visited.add(node) 5 | for neighbor in graph[node]: 6 | dfs(graph, neighbor, visited) 7 | -------------------------------------------------------------------------------- /Dijkstrasalgorithm.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | 3 | def dijkstra(graph, start): 4 | distances = {node: float('infinity') for node in graph} 5 | distances[start] = 0 6 | priority_queue = [(0, start)] 7 | 8 | while priority_queue: 9 | current_distance, current_node = heapq.heappop(priority_queue) 10 | 11 | if current_distance > distances[current_node]: 12 | continue 13 | 14 | for neighbor, weight in graph[current_node].items(): 15 | distance = current_distance + weight 16 | if distance < distances[neighbor]: 17 | distances[neighbor] = distance 18 | heapq.heappush(priority_queue, (distance, neighbor)) 19 | return distances 20 | -------------------------------------------------------------------------------- /Hashtableusage.py: -------------------------------------------------------------------------------- 1 | my_dict = {} 2 | my_dict['name'] = 'John' 3 | my_dict['age'] = 30 4 | 5 | print("Name:", my_dict['name']) 6 | print("Age:", my_dict['age']) 7 | my_dict = {} 8 | my_dict['name'] = 'John' 9 | my_dict['age'] = 30 10 | 11 | print("Name:", my_dict['name']) 12 | print("Age:", my_dict['age']) 13 | -------------------------------------------------------------------------------- /Knapsackproblem.py: -------------------------------------------------------------------------------- 1 | def knapsack(values, weights, capacity): 2 | n = len(values) 3 | dp = [[0 for _ in range(capacity + 1)] for _ in range(n + 1)] 4 | 5 | for i in range(n + 1): 6 | for w in range(capacity + 1): 7 | if i == 0 or w 8 | -------------------------------------------------------------------------------- /Linkedlistimplementation.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self, data): 3 | self.data = data 4 | self.next = None 5 | 6 | class LinkedList: 7 | def __init__(self): 8 | self.head = None 9 | 10 | def append(self, data): 11 | new_node = Node(data) 12 | if not self.head: 13 | self.head = new_node 14 | else: 15 | current = self.head 16 | while current.next: 17 | current = current.next 18 | current.next = new_node 19 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Python- 2 | DSA in python 3 | -------------------------------------------------------------------------------- /armstrong.py: -------------------------------------------------------------------------------- 1 | def is_armstrong_number(number): 2 | # Calculate the number of digits in the given number 3 | num_str = str(number) 4 | num_digits = len(num_str) 5 | 6 | # Calculate the sum of each digit raised to the power of the number of digits 7 | sum_of_digits = sum(int(digit) ** num_digits for digit in num_str) 8 | 9 | # Check if the number is an Armstrong number 10 | return number == sum_of_digits 11 | 12 | # Input from the user 13 | user_input = input("Enter a number: ") 14 | 15 | try: 16 | number = int(user_input) 17 | if is_armstrong_number(number): 18 | print(f"{number} is an Armstrong number.") 19 | else: 20 | print(f"{number} is not an Armstrong number.") 21 | except ValueError: 22 | print("Please enter a valid integer.") 23 | -------------------------------------------------------------------------------- /binarysearch.py: -------------------------------------------------------------------------------- 1 | # Binary Search in python 2 | 3 | 4 | def binarySearch(array, x, low, high): 5 | 6 | # Repeat until the pointers low and high meet each other 7 | while low <= high: 8 | 9 | mid = low + (high - low)//2 10 | 11 | if array[mid] == x: 12 | return mid 13 | 14 | elif array[mid] < x: 15 | low = mid + 1 16 | 17 | else: 18 | high = mid - 1 19 | 20 | return -1 21 | 22 | 23 | array = [3, 4, 5, 6, 7, 8, 9] 24 | x = 4 25 | 26 | result = binarySearch(array, x, 0, len(array)-1) 27 | 28 | if result != -1: 29 | print("Element is present at index " + str(result)) 30 | else: 31 | print("Not found") 32 | -------------------------------------------------------------------------------- /bubblesort.py: -------------------------------------------------------------------------------- 1 | # Python3 program for Bubble Sort Algorithm Implementation 2 | def bubbleSort(arr): 3 | 4 | n = len(arr) 5 | 6 | # For loop to traverse through all 7 | # element in an array 8 | for i in range(n): 9 | for j in range(0, n - i - 1): 10 | 11 | # Range of the array is from 0 to n-i-1 12 | # Swap the elements if the element found 13 | #is greater than the adjacent element 14 | if arr[j] > arr[j + 1]: 15 | arr[j], arr[j + 1] = arr[j + 1], arr[j] 16 | 17 | # Driver code 18 | 19 | # Example to test the above code 20 | arr = [ 2, 1, 10, 23 ] 21 | 22 | bubbleSort(arr) 23 | 24 | print("Sorted array is:") 25 | for i in range(len(arr)): 26 | print("%d" % arr[i]) 27 | -------------------------------------------------------------------------------- /factorial.py: -------------------------------------------------------------------------------- 1 | num = int(input("Enter a number: ")) 2 | # 7 3 | factorial = 1 4 | if num < 0: 5 | print("Sorry, factorial does not exist for negative numbers") 6 | elif num == 0: 7 | print("The factorial of 0 is 1") 8 | else: 9 | for i in range(1,num + 1): 10 | factorial = factorial*i 11 | print("The factorial of",num,"is",factorial) 12 | # 5040 13 | -------------------------------------------------------------------------------- /fibonacci_series.py: -------------------------------------------------------------------------------- 1 | def generate_fibonacci(n): 2 | fibonacci_series = [] 3 | a, b = 0, 1 4 | for _ in range(n): 5 | fibonacci_series.append(a) 6 | a, b = b, a + b 7 | return fibonacci_series 8 | 9 | # Input the number of terms you want in the series 10 | n = int(input("Enter the number of Fibonacci terms: ")) 11 | 12 | if n <= 0: 13 | print("Please enter a positive integer.") 14 | else: 15 | result = generate_fibonacci(n) 16 | print("Fibonacci series:") 17 | for term in result: 18 | print(term) 19 | -------------------------------------------------------------------------------- /gcd.py: -------------------------------------------------------------------------------- 1 | def gcd(a, b): 2 | 3 | if (a == 0): 4 | return b 5 | if (b == 0): 6 | return a 7 | 8 | if (a == b): 9 | return a 10 | 11 | if (a > b): 12 | return gcd(a-b, b) 13 | return gcd(a, b-a) 14 | 15 | a = 98 16 | b = 56 17 | if(gcd(a, b)): 18 | print('GCD of', a, 'and', b, 'is', gcd(a, b)) 19 | else: 20 | print('not found') 21 | -------------------------------------------------------------------------------- /insert_into_bst.py: -------------------------------------------------------------------------------- 1 | # Python program to show how to insert a value in the binary search tree 2 | 3 | # Creating a constructor class that will create the node object 4 | class Node: 5 | # Defining the method to create a new node and the left and right pointers of this node. 6 | def __init__(self, val): 7 | self.val = val 8 | self.left = None 9 | self.right = None 10 | 11 | 12 | # Defining a function to insert the given value of x into the tree 13 | def insert(root, x): 14 | # If the given tree is empty, we will return a node with the given value 15 | if root is None: 16 | return Node(x) 17 | else: 18 | # We will check if the value of the current node is equal to the value we want to insert 19 | if root.val == x: 20 | # If yes, then there is no need to modify the tree, and we will return the root node 21 | return root 22 | # If the value of x is greater than the value of the root node 23 | elif root.val < x: 24 | # We will insert the node in the right subtree 25 | root.right = insert(root.right, x) 26 | # If the value of x is smaller than the value of the root node 27 | else: 28 | # We will insert the node in the left subtree 29 | root.left = insert(root.left, x) 30 | return root 31 | 32 | 33 | # Creating a function to traverse the tree to check the final results 34 | def inorderTraversal(root): 35 | if root: 36 | inorderTraversal(root.left) 37 | print(root.val, end = " ") 38 | inorderTraversal(root.right) 39 | 40 | 41 | # Creating a binary search tree and inserting x in the tree 42 | root = Node(9) 43 | root.left = Node(1) 44 | root.right = Node(10) 45 | root.left.left = Node(0) 46 | root.left.right = Node(3) 47 | root.left.right.right = Node(4) 48 | print("The tree before insertion: ") 49 | inorderTraversal(root) 50 | print("\n") 51 | x = 5 52 | v = insert(root, x) 53 | print("The tree after insertion: ") 54 | inorderTraversal(v) 55 | -------------------------------------------------------------------------------- /insertionsort.py: -------------------------------------------------------------------------------- 1 | def insertionSort(arr): 2 | n = len(arr) # Get the length of the array 3 | 4 | if n <= 1: 5 | return # If the array has 0 or 1 element, it is already sorted, so return 6 | 7 | for i in range(1, n): # Iterate over the array starting from the second element 8 | key = arr[i] # Store the current element as the key to be inserted in the right position 9 | j = i-1 10 | while j >= 0 and key < arr[j]: # Move elements greater than key one position ahead 11 | arr[j+1] = arr[j] # Shift elements to the right 12 | j -= 1 13 | arr[j+1] = key # Insert the key in the correct position 14 | 15 | # Sorting the array [12, 11, 13, 5, 6] using insertionSort 16 | arr = [12, 11, 13, 5, 6] 17 | insertionSort(arr) 18 | print(arr) 19 | -------------------------------------------------------------------------------- /linearsearch.py: -------------------------------------------------------------------------------- 1 | # Linear Search in Python 2 | 3 | 4 | def linearSearch(array, n, x): 5 | 6 | # Going through array sequencially 7 | for i in range(0, n): 8 | if (array[i] == x): 9 | return i 10 | return -1 11 | 12 | 13 | array = [2, 4, 0, 1, 9] 14 | x = 1 15 | n = len(array) 16 | result = linearSearch(array, n, x) 17 | if(result == -1): 18 | print("Element not found") 19 | else: 20 | print("Element found at index: ", result) 21 | -------------------------------------------------------------------------------- /maximumofthree.py: -------------------------------------------------------------------------------- 1 | def maximum(a, b, c): 2 | 3 | if (a >= b) and (a >= c): 4 | largest = a 5 | 6 | elif (b >= a) and (b >= c): 7 | largest = b 8 | else: 9 | largest = c 10 | 11 | return largest 12 | 13 | 14 | a = int(input("Enter a number: ")) 15 | # Input1: 10 16 | b = int(input("Enter a number: ")) 17 | # Input2: 14 18 | c = int(input("Enter a number: ")) 19 | # Input3: 12 20 | print(maximum(a, b, c)) 21 | # Output: 14 22 | -------------------------------------------------------------------------------- /mergesort.py: -------------------------------------------------------------------------------- 1 | def merge(left, right): 2 | # If the first array is empty, then nothing needs 3 | # to be merged, and you can return the second array as the result 4 | if len(left) == 0: 5 | return right 6 | 7 | # If the second array is empty, then nothing needs 8 | # to be merged, and you can return the first array as the result 9 | if len(right) == 0: 10 | return left 11 | 12 | result = [] 13 | index_left = index_right = 0 14 | 15 | # Now go through both arrays until all the elements 16 | # make it into the resultant array 17 | while len(result) < len(left) + len(right): 18 | # The elements need to be sorted to add them to the 19 | # resultant array, so you need to decide whether to get 20 | # the next element from the first or the second array 21 | if left[index_left] <= right[index_right]: 22 | result.append(left[index_left]) 23 | index_left += 1 24 | else: 25 | result.append(right[index_right]) 26 | index_right += 1 27 | 28 | # If you reach the end of either array, then you can 29 | # add the remaining elements from the other array to 30 | # the result and break the loop 31 | if index_right == len(right): 32 | result += left[index_left:] 33 | break 34 | 35 | if index_left == len(left): 36 | result += right[index_right:] 37 | break 38 | 39 | return result 40 | -------------------------------------------------------------------------------- /palindrome.py: -------------------------------------------------------------------------------- 1 | def is_palindrome(input_str): 2 | # Remove spaces and convert the string to lowercase 3 | input_str = input_str.replace(" ", "").lower() 4 | 5 | # Compare the original string with its reverse 6 | return input_str == input_str[::-1] 7 | 8 | # Input from the user 9 | user_input = input("Enter a string: ") 10 | 11 | if is_palindrome(user_input): 12 | print("It's a palindrome!") 13 | else: 14 | print("It's not a palindrome.") 15 | -------------------------------------------------------------------------------- /perfect_number.py: -------------------------------------------------------------------------------- 1 | def is_perfect_number(number): 2 | divisors_sum = sum([i for i in range(1, number) if number % i == 0]) 3 | return divisors_sum == number 4 | 5 | # Input from the user 6 | user_input = input("Enter a number: ") 7 | 8 | try: 9 | number = int(user_input) 10 | if is_perfect_number(number): 11 | print(f"{number} is a perfect number.") 12 | else: 13 | print(f"{number} is not a perfect number.") 14 | except ValueError: 15 | print("Please enter a valid integer.") 16 | -------------------------------------------------------------------------------- /prime_number.py: -------------------------------------------------------------------------------- 1 | def is_prime(number): 2 | if number <= 1: 3 | return False 4 | for i in range(2, int(number**0.5) + 1): 5 | if number % i == 0: 6 | return False 7 | return True 8 | 9 | # Input from the user 10 | user_input = input("Enter a number: ") 11 | 12 | try: 13 | number = int(user_input) 14 | if is_prime(number): 15 | print(f"{number} is a prime number.") 16 | else: 17 | print(f"{number} is not a prime number.") 18 | except ValueError: 19 | print("Please enter a valid integer.") 20 | -------------------------------------------------------------------------------- /queue.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | class Queue: 4 | def __init__(self): 5 | self.items = deque() 6 | 7 | def enqueue(self, item): 8 | self.items.append(item) 9 | 10 | def dequeue(self): 11 | if not self.is_empty(): 12 | return self.items.popleft() 13 | return None 14 | 15 | def is_empty(self): 16 | return len(self.items) == 0 17 | -------------------------------------------------------------------------------- /quicksort.py: -------------------------------------------------------------------------------- 1 | # Python program for implementation of Quicksort Sort 2 | 3 | # This implementation utilizes pivot as the last element in the nums list 4 | # It has a pointer to keep track of the elements smaller than the pivot 5 | # At the very end of partition() function, the pointer is swapped with the pivot 6 | # to come up with a "sorted" nums relative to the pivot 7 | 8 | 9 | # Function to find the partition position 10 | def partition(array, low, high): 11 | 12 | # choose the rightmost element as pivot 13 | pivot = array[high] 14 | 15 | # pointer for greater element 16 | i = low - 1 17 | 18 | # traverse through all elements 19 | # compare each element with pivot 20 | for j in range(low, high): 21 | if array[j] <= pivot: 22 | 23 | # If element smaller than pivot is found 24 | # swap it with the greater element pointed by i 25 | i = i + 1 26 | 27 | # Swapping element at i with element at j 28 | (array[i], array[j]) = (array[j], array[i]) 29 | 30 | # Swap the pivot element with the greater element specified by i 31 | (array[i + 1], array[high]) = (array[high], array[i + 1]) 32 | 33 | # Return the position from where partition is done 34 | return i + 1 35 | 36 | # function to perform quicksort 37 | 38 | 39 | def quickSort(array, low, high): 40 | if low < high: 41 | 42 | # Find pivot element such that 43 | # element smaller than pivot are on the left 44 | # element greater than pivot are on the right 45 | pi = partition(array, low, high) 46 | 47 | # Recursive call on the left of pivot 48 | quickSort(array, low, pi - 1) 49 | 50 | # Recursive call on the right of pivot 51 | quickSort(array, pi + 1, high) 52 | 53 | 54 | data = [1, 7, 4, 1, 10, 9, -2] 55 | print("Unsorted Array") 56 | print(data) 57 | 58 | size = len(data) 59 | 60 | quickSort(data, 0, size - 1) 61 | 62 | print('Sorted Array in Ascending Order:') 63 | print(data) 64 | -------------------------------------------------------------------------------- /searching_in_bst.py: -------------------------------------------------------------------------------- 1 | # Python program to implement search operation in the binary search tree 2 | 3 | # Creating a constructor class that will create the node object 4 | class Node: 5 | # Defining the method to create a new node and the left and right pointers of this node. 6 | def __init__(self, val): 7 | self.val = val 8 | self.left = None 9 | self.right = None 10 | 11 | # Defining a function that will search the given value of x in the tree 12 | def search(root, x): 13 | 14 | # The base conditions are 15 | # If the given root is a Null Node 16 | # Or if the value we are searching for is present at the root only 17 | if root is None or root.val == x: 18 | return root.val 19 | 20 | # If the value of x is greater than the value of the root node 21 | if root.val < x: 22 | # We will search in the right subtree 23 | return search(root.right, x) 24 | 25 | # If the value of x is smaller than the value of the root node 26 | # We will search in the left subtree 27 | return search(root.left, x) 28 | 29 | # Creating a binary search tree and searching for x in the tree 30 | root = Node(9) 31 | root.left = Node(1) 32 | root.right = Node(10) 33 | root.left.left = Node(0) 34 | root.left.right = Node(3) 35 | root.left.right.right = Node(4) 36 | x = 4 37 | v = search(root, x) 38 | print("The node we are searching for is present in the given BST: ", v) 39 | -------------------------------------------------------------------------------- /selectionsort.py: -------------------------------------------------------------------------------- 1 | # Selection Sort algorithm in Python 2 | def selectionSort(array, size): 3 | 4 | for s in range(size): 5 | min_idx = s 6 | 7 | for i in range(s + 1, size): 8 | 9 | # For sorting in descending order 10 | # for minimum element in each loop 11 | if array[i] < array[min_idx]: 12 | min_idx = i 13 | 14 | # Arranging min at the correct position 15 | (array[s], array[min_idx]) = (array[min_idx], array[s]) 16 | 17 | # Driver code 18 | data = [ 7, 2, 1, 6 ] 19 | size = len(data) 20 | selectionSort(data, size) 21 | 22 | print('Sorted Array in Ascending Order is :') 23 | print(data) 24 | -------------------------------------------------------------------------------- /stack.py: -------------------------------------------------------------------------------- 1 | class Stack: 2 | def __init__(self): 3 | self.items = [] 4 | 5 | def push(self, item): 6 | self.items.append(item) 7 | 8 | def pop(self): 9 | if not self.is_empty(): 10 | return self.items.pop() 11 | return None 12 | 13 | def is_empty(self): 14 | return len(self.items) == 0 15 | -------------------------------------------------------------------------------- /string_anagram.py: -------------------------------------------------------------------------------- 1 | def check(s1, s2): 2 | 3 | if(sorted(s1)== sorted(s2)): 4 | print("The strings are anagrams.") 5 | else: 6 | print("The strings aren't anagrams.") 7 | 8 | s1 = input("Enter string1: ") 9 | # input1: "listen" 10 | s2 = input("Enter string2: ") 11 | # input2: "silent" 12 | check(s1, s2) 13 | # Output: the strings are anagrams. 14 | -------------------------------------------------------------------------------- /trianglepattern.py: -------------------------------------------------------------------------------- 1 | def myfunc(n): 2 | k = n - 1 3 | for i in range(0, n): 4 | for j in range(0, k): 5 | print(end=" ") 6 | k = k - 1 7 | for j in range(0, i+1): 8 | print("* ", end="") 9 | print("\r") 10 | n = 5 11 | myfunc(n) 12 | --------------------------------------------------------------------------------