├── 01.Calculate_Circle.py ├── 30_Days_of_Python ├── Day_01.ipynb ├── Day_02 ├── Day_03 ├── Day_04 ├── Day_05 ├── Day_06 ├── Day_07 ├── Day_08 ├── Day_09 └── Day_10 ├── Code_Bunch.py ├── DSA_Bunch.py ├── LeetCode_Questions └── 997_Squarred_a_sorted_array.py ├── README.md ├── Top_20_Python_Coding_Interview_QuestionSimple ├── P01.py ├── P02.py ├── P03.py ├── P04.py ├── P05.py ├── P06.py ├── P07.py ├── P08.py ├── P09.py ├── P10.py ├── P11.py ├── P12.py ├── P13.py ├── P14.py ├── P15.py ├── P16.py ├── P17.py ├── P18.py ├── P19.py └── P20.py ├── fruits.txt ├── main.py ├── new.py ├── passwordmanager.py └── travelGPT.py /01.Calculate_Circle.py: -------------------------------------------------------------------------------- 1 | pi = 3.142 2 | radius = 5 3 | 4 | # Program to calculate the Circumfrance of the Circle 5 | 6 | def Circle(): 7 | area = pi * (radius) ** 2 8 | print("The Area of the Circle", area) 9 | 10 | Circle_Circumfrance = 2 * pi * radius 11 | print("The Circumfrance of the Circle", Circle_Circumfrance) 12 | 13 | Circle() -------------------------------------------------------------------------------- /30_Days_of_Python/Day_01.ipynb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AzaamAhmed/StudyPython/b973907cf419d24d1de35043bc4274c7f72f7120/30_Days_of_Python/Day_01.ipynb -------------------------------------------------------------------------------- /30_Days_of_Python/Day_02: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AzaamAhmed/StudyPython/b973907cf419d24d1de35043bc4274c7f72f7120/30_Days_of_Python/Day_02 -------------------------------------------------------------------------------- /30_Days_of_Python/Day_03: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AzaamAhmed/StudyPython/b973907cf419d24d1de35043bc4274c7f72f7120/30_Days_of_Python/Day_03 -------------------------------------------------------------------------------- /30_Days_of_Python/Day_04: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AzaamAhmed/StudyPython/b973907cf419d24d1de35043bc4274c7f72f7120/30_Days_of_Python/Day_04 -------------------------------------------------------------------------------- /30_Days_of_Python/Day_05: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AzaamAhmed/StudyPython/b973907cf419d24d1de35043bc4274c7f72f7120/30_Days_of_Python/Day_05 -------------------------------------------------------------------------------- /30_Days_of_Python/Day_06: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AzaamAhmed/StudyPython/b973907cf419d24d1de35043bc4274c7f72f7120/30_Days_of_Python/Day_06 -------------------------------------------------------------------------------- /30_Days_of_Python/Day_07: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AzaamAhmed/StudyPython/b973907cf419d24d1de35043bc4274c7f72f7120/30_Days_of_Python/Day_07 -------------------------------------------------------------------------------- /30_Days_of_Python/Day_08: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AzaamAhmed/StudyPython/b973907cf419d24d1de35043bc4274c7f72f7120/30_Days_of_Python/Day_08 -------------------------------------------------------------------------------- /30_Days_of_Python/Day_09: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AzaamAhmed/StudyPython/b973907cf419d24d1de35043bc4274c7f72f7120/30_Days_of_Python/Day_09 -------------------------------------------------------------------------------- /30_Days_of_Python/Day_10: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AzaamAhmed/StudyPython/b973907cf419d24d1de35043bc4274c7f72f7120/30_Days_of_Python/Day_10 -------------------------------------------------------------------------------- /Code_Bunch.py: -------------------------------------------------------------------------------- 1 | """ 2 | This is a collection of Python code snippets for beginner & Advanced Python codes. 3 | I will comment it after I finish the code by myself. 4 | 5 | """ 6 | 7 | 8 | 9 | 10 | #finding the calculate of the factorial of a number 11 | 12 | def factorial(n): 13 | if n == 0: 14 | return 1 15 | return n * factorial(n-1) 16 | print(factorial(6)) 17 | 18 | #counting the upper case 19 | 20 | def count_upper_case(s): 21 | return sum(1 for char in s if char.isupper()) 22 | 23 | print(count_upper_case("Hello World I am a Python Developer Welcome to the World of Python")) 24 | 25 | # Binary Search 26 | def binary_search(arr, target): 27 | low, high = 0, len(arr) - 1 28 | while low <= high: 29 | mid = (low + high) // 2 30 | if arr[mid] < target: 31 | low = mid + 1 32 | elif arr[mid] > target: 33 | high = mid - 1 34 | else: 35 | return mid 36 | return -1 37 | 38 | print(binary_search([1, 2, 3, 4, 5], 3)) 39 | 40 | 41 | # Flatten a nested list 42 | def flatten(nested_list): 43 | flat_list = [] 44 | for item in nested_list: 45 | if isinstance(item, list): 46 | flat_list.extend(flatten(item)) 47 | else: 48 | flat_list.append(item) 49 | return flat_list 50 | 51 | print(flatten([1, [2, [3, 4], 5], 6])) 52 | 53 | # Finding the maximum number in a list 54 | 55 | def max_num(arr): 56 | max = arr[0] 57 | for i in arr: 58 | if i > max: 59 | max = i 60 | return max 61 | 62 | # Finding the minimum number in a list 63 | 64 | def min_num(arr): 65 | min = arr[0] 66 | for i in arr: 67 | if i < min: 68 | min = i 69 | return min 70 | 71 | 72 | #program to check if a binary tree is balanced 73 | 74 | class Node: 75 | def __init__(self, value): 76 | self.value = value 77 | self.left = None 78 | self.right = None 79 | 80 | def is_balanced(root): 81 | if not root: 82 | return True 83 | 84 | def height(node): 85 | if not node: 86 | return 0 87 | return 1 + max(height(node.left), height(node.right)) 88 | 89 | return abs(height(root.left) - height(root.right)) <= 1 90 | 91 | root = Node(1) 92 | root.left = Node(2) 93 | root.right = Node(3) 94 | print(is_balanced(root)) 95 | 96 | #program to find the maximum subarray sum 97 | 98 | def max_subarray_sum(arr): 99 | max_sum = current_sum = arr[0] 100 | for num in arr[1:]: 101 | current_sum = max(num, current_sum + num) 102 | max_sum = max(max_sum, current_sum) 103 | return max_sum 104 | 105 | print(max_subarray_sum([-2, 1, -3, 4, -1, 2, 1, -5, 4])) 106 | 107 | #program to find the longest common prefix 108 | 109 | def longest_common_prefix(strs): 110 | if not strs: 111 | return "" 112 | for i, letter_group in enumerate(zip(*strs)): 113 | if len(set(letter_group)) > 1: 114 | return strs[0][:i] 115 | return min(strs) 116 | 117 | print(longest_common_prefix(["flower", "flow", "flight"])) 118 | print(longest_common_prefix(["dog", "racecar", "car"])) 119 | print(longest_common_prefix(["ab", "a"])) 120 | 121 | 122 | # program to find the intersection of two sets 123 | 124 | def intersection(set1, set2): 125 | return set1 & set2 126 | 127 | print(intersection({1, 2, 3}, {2, 3, 4})) 128 | 129 | 130 | # program to find the union of two sets 131 | 132 | def calculator(a, b, operation): 133 | if operation == 'add': 134 | return a + b 135 | elif operation == 'subtract': 136 | return a - b 137 | elif operation == 'multiply': 138 | return a * b 139 | elif operation == 'divide': 140 | return a / b if b != 0 else "Cannot divide by zero" 141 | else: 142 | return "Invalid operation" 143 | 144 | print(calculator(5, 3, 'add')) 145 | 146 | # convert celsius to fahrenheit 147 | 148 | def celsius_to_fahrenheit(temps): 149 | return [(temp * 9/5) + 32 for temp in temps] 150 | print(celsius_to_fahrenheit([0, 20, 37])) 151 | 152 | 153 | # implement a queue using collection.queue 154 | 155 | from collections import deque 156 | 157 | class Queue: 158 | def __init__(self): 159 | self.queue = deque() 160 | 161 | def enqueue(self, item): 162 | self.queue.append(item) 163 | 164 | def dequeue(self): 165 | return self.queue.popleft() if self.queue else None 166 | 167 | q = Queue() 168 | q.enqueue(1) 169 | q.enqueue(2) 170 | print(q.dequeue()) 171 | 172 | # program to check if a string is a palindrome 173 | 174 | def is_palindrome(string): 175 | reversed_string = string[::-1] 176 | return string == reversed_string 177 | 178 | word = "madam" 179 | if is_palindrome(word): 180 | print(f"{word} is a palindrome") 181 | else: 182 | print(f"{word} is not a palindrome") 183 | 184 | # program to find the factorial of a number 185 | 186 | def factorial(n): 187 | if n == 0: 188 | return 1 189 | else: 190 | return n * factorial(n-1) 191 | 192 | number = 5 193 | result = factorial(number) 194 | print(f"The factorial of {number} is {result}") 195 | 196 | 197 | # program to find the largest number in a list 198 | 199 | def find_largest(numbers): 200 | largest = numbers[0] 201 | for num in numbers: 202 | if num > largest: 203 | largest = num 204 | return largest 205 | 206 | nums = [10, 5, 8, 20, 3] 207 | largest_num = find_largest(nums) 208 | print(f"The largest number is {largest_num}") 209 | 210 | 211 | # program to reverse a string. 212 | 213 | def reverse_string(string): 214 | return string[::-1] 215 | 216 | text = "Hello, World!" 217 | reversed_text = reverse_string(text) 218 | print(reversed_text) 219 | 220 | 221 | # program to find the frequency of numbers in a list 222 | 223 | def count_frequency(numbers): 224 | frequency = {} 225 | for num in numbers: 226 | if num in frequency: 227 | frequency[num] += 1 228 | else: 229 | frequency[num] = 1 230 | return frequency 231 | 232 | nums = [1, 2, 3, 2, 1, 3, 2, 4, 5, 4] 233 | frequency_count = count_frequency(nums) 234 | print(frequency_count) 235 | 236 | # program to check if a number is prime 237 | 238 | def is_prime(number): 239 | if number < 2: 240 | return False 241 | for i in range(2, int(number**0.5) + 1): 242 | if number % i == 0: 243 | return False 244 | return True 245 | 246 | num = 17 247 | if is_prime(num): 248 | print(f"{num} is a prime number") 249 | else: 250 | print(f"{num} is not a prime number") 251 | 252 | 253 | 254 | 255 | # program to find the common elements between two lists 256 | 257 | def find_common_elements(list1, list2): 258 | common_elements = [] 259 | for item in list1: 260 | if item in list2: 261 | common_elements.append(item) 262 | return common_elements 263 | 264 | list_a = [1, 2, 3, 4, 5] 265 | list_b = [4, 5, 6, 7, 8] 266 | common = find_common_elements(list_a, list_b) 267 | print(common) 268 | 269 | 270 | # Python program to sort a list of elements using the bubble sort algorithm. 271 | 272 | def bubble_sort(elements): 273 | n = len(elements) 274 | for i in range(n - 1): 275 | for j in range(n - i - 1): 276 | if elements[j] > elements[j + 1]: 277 | elements[j], elements[j + 1] = elements[j + 1], elements[j] 278 | 279 | nums = [5, 2, 8, 1, 9] 280 | bubble_sort(nums) 281 | print(nums) 282 | 283 | 284 | # program to remove duplicates from a list 285 | 286 | def remove_duplicates(numbers): 287 | unique_numbers = [] 288 | for num in numbers: 289 | if num not in unique_numbers: 290 | unique_numbers.append(num) 291 | return unique_numbers 292 | 293 | # Test the function 294 | nums = [1, 2, 3, 2, 1, 3, 2, 4, 5, 4] 295 | unique_nums = remove_duplicates(nums) 296 | print(unique_nums) 297 | 298 | # fibbonaci sequence upto a given number of terms 299 | 300 | def fibonacci(n): 301 | fib_seq = [0, 1] 302 | while len(fib_seq) < n: 303 | fib_seq.append(fib_seq[-1] + fib_seq[-2]) 304 | return fib_seq 305 | 306 | num_terms = int(input("Enter the number of terms: ")) 307 | fibonacci_seq = fibonacci(num_terms) 308 | print("Fibonacci sequence:", fibonacci_seq) 309 | 310 | 311 | # palindrome partitioning 312 | 313 | def partition(s: str) -> List[List[str]]: 314 | def is_palindrome(sub: str) -> bool: 315 | return sub == sub[::-1] 316 | 317 | def backtrack(start: int, path: List[str]): 318 | if start == len(s): 319 | result.append(path[:]) 320 | return 321 | for end in range(start + 1, len(s) + 1): 322 | substring = s[start:end] 323 | if is_palindrome(substring): 324 | path.append(substring) 325 | backtrack(end, path) 326 | path.pop() 327 | 328 | result = [] 329 | backtrack(0, []) 330 | return result 331 | 332 | 333 | # LRU Cache implementation 334 | 335 | from collections import OrderedDict 336 | 337 | class LRUCache: 338 | def __init__(self, capacity: int): 339 | self.cache = OrderedDict() 340 | self.capacity = capacity 341 | 342 | def get(self, key: int) -> int: 343 | if key not in self.cache: 344 | return -1 345 | self.cache.move_to_end(key) 346 | return self.cache[key] 347 | 348 | def put(self, key: int, value: int) -> None: 349 | if key in self.cache: 350 | self.cache.move_to_end(key) 351 | self.cache[key] = value 352 | if len(self.cache) > self.capacity: 353 | self.cache.popitem(last=False) 354 | 355 | 356 | # merge intervals 357 | 358 | def merge(intervals: List[List[int]]) -> List[List[int]]: 359 | if not intervals: 360 | return [] 361 | 362 | intervals.sort(key=lambda x: x[0]) 363 | merged = [intervals[0]] 364 | for current in intervals[1:]: 365 | last = merged[-1] 366 | if current[0] <= last[1]: 367 | last[1] = max(last[1], current[1]) 368 | else: 369 | merged.append(current) 370 | return merged 371 | 372 | 373 | 374 | # implement a min heap 375 | 376 | class MinHeap: 377 | def __init__(self): 378 | self.heap = [] 379 | 380 | def insert(self, val): 381 | self.heap.append(val) 382 | self._bubble_up(len(self.heap) - 1) 383 | 384 | def get_min(self): 385 | if not self.heap: 386 | return None 387 | return self.heap[0] 388 | 389 | def extract_min(self): 390 | if not self.heap: 391 | return None 392 | if len(self.heap) == 1: 393 | return self.heap.pop() 394 | min_val = self.heap[0] 395 | self.heap[0] = self.heap.pop() 396 | self._bubble_down(0) 397 | return min_val 398 | 399 | def heapify(self, arr): 400 | self.heap = arr[:] 401 | for i in reversed(range(len(arr) // 2)): 402 | self._bubble_down(i) 403 | 404 | def _bubble_up(self, index): 405 | parent_index = (index - 1) // 2 406 | if index > 0 and self.heap[index] < self.heap[parent_index]: 407 | self.heap[index], self.heap[parent_index] = self.heap[parent_index], self.heap[index] 408 | self._bubble_up(parent_index) 409 | 410 | def _bubble_down(self, index): 411 | smallest = index 412 | left = 2 * index + 1 413 | right = 2 * index + 2 414 | if left < len(self.heap) and self.heap[left] < self.heap[smallest]: 415 | smallest = left 416 | if right < len(self.heap) and self.heap[right] < self.heap[smallest]: 417 | smallest = right 418 | if smallest != index: 419 | self.heap[index], self.heap[smallest] = self.heap[smallest], self.heap[index] 420 | self._bubble_down(smallest) 421 | 422 | 423 | # implement a max heap 424 | 425 | class MaxHeap: 426 | def __init__(self): 427 | self.heap = [] 428 | 429 | def insert(self, val): 430 | self.heap.append(val) 431 | self._bubble_up(len(self.heap) - 1) 432 | 433 | def get_max(self): 434 | if not self.heap: 435 | return None 436 | return self.heap[0] 437 | 438 | def extract_max(self): 439 | if not self.heap: 440 | return None 441 | if len(self.heap) == 1: 442 | return self.heap.pop() 443 | max_val = self.heap[0] 444 | self.heap[0] = self.heap.pop() 445 | self._bubble_down(0) 446 | return max_val 447 | 448 | def heapify(self, arr): 449 | self.heap = arr[:] 450 | for i in reversed(range(len(arr) // 2)): 451 | self._bubble_down(i) 452 | 453 | def _bubble_up(self, index): 454 | parent_index = (index - 1) // 2 455 | if index > 0 and self.heap[index] > self.heap[parent_index]: 456 | self.heap[index], self.heap[parent_index] = self.heap[parent_index], self.heap[index] 457 | self._bubble_up(parent_index) 458 | 459 | def _bubble_down(self, index): 460 | largest = index 461 | left = 2 * index + 1 462 | right = 2 * index + 2 463 | if left < len(self.heap) and self.heap[left] > self.heap[largest]: 464 | largest = left 465 | if right < len(self.heap) and self.heap[right] > self.heap[largest]: 466 | largest = right 467 | if largest != index: 468 | self.heap[index], self.heap[largest] = self.heap[largest], self.heap[index] 469 | self._bubble_down(largest) 470 | 471 | 472 | # implement a stack using two queues 473 | 474 | from collections import deque 475 | 476 | class Stack: 477 | def __init__(self): 478 | self.queue1 = deque() 479 | self.queue2 = deque() 480 | 481 | def push(self, val): 482 | self.queue1.append(val) 483 | 484 | def pop(self): 485 | if not self.queue1: 486 | return None 487 | while len(self.queue1) > 1: 488 | self.queue2.append(self.queue1.popleft()) 489 | val = self.queue1.popleft() 490 | self.queue1, self.queue2 = self.queue2, self.queue1 491 | return val 492 | 493 | def top(self): 494 | if not self.queue1: 495 | return None 496 | while len(self.queue1) > 1: 497 | self.queue2.append(self.queue1.popleft()) 498 | val = self.queue1.popleft() 499 | self.queue2.append(val) 500 | self.queue1, self.queue2 = self.queue2, self.queue1 501 | return val 502 | 503 | def is_empty(self): 504 | return not self.queue1 505 | 506 | 507 | # implement a Hash Table 508 | 509 | class HashTable: 510 | def __init__(self, capacity=100): 511 | self.capacity = capacity 512 | self.table = [[] for _ in range(capacity)] 513 | 514 | def _hash(self, key): 515 | return hash(key) % self.capacity 516 | 517 | def put(self, key, value): 518 | index = self._hash(key) 519 | for i, (k, v) in enumerate(self.table[index]): 520 | if k == key: 521 | self.table[index][i] = (key, value) 522 | return 523 | self.table[index].append((key, value)) 524 | 525 | def get(self, key): 526 | index = self._hash(key) 527 | for k, v in self.table[index]: 528 | if k == key: 529 | return v 530 | return None 531 | 532 | def remove(self, key): 533 | index = self._hash(key) 534 | self.table[index] = [(k, v) for k, v in self.table[index] if k != key] 535 | 536 | 537 | # implement a Trie(Prefix Tree) 538 | 539 | class TrieNode: 540 | def __init__(self): 541 | self.children = {} 542 | self.is_end_of_word = False 543 | 544 | class Trie: 545 | def __init__(self): 546 | self.root = TrieNode() 547 | 548 | def insert(self, word): 549 | node = self.root 550 | for char in word: 551 | node = node.children.setdefault(char, TrieNode()) 552 | node.is_end_of_word = True 553 | 554 | def search(self, word): 555 | node = self._find_node(word) 556 | return node is not None and node.is_end_of_word 557 | 558 | def starts_with(self, prefix): 559 | return self._find_node(prefix) is not None 560 | 561 | def _find_node(self, prefix): 562 | node = self.root 563 | for char in prefix: 564 | if char not in node.children: 565 | return None 566 | node = node.children[char] 567 | return node 568 | 569 | 570 | # implement a Binary Search Tree 571 | 572 | class TreeNode: 573 | def __init__(self, val=0, left=None, right=None): 574 | self.val = val 575 | self.left = left 576 | self.right = right 577 | 578 | 579 | # implement a Graph using adjacency list 580 | 581 | class Graph: 582 | def __init__(self): 583 | self.adjacency_list = {} 584 | 585 | def add_vertex(self, vertex): 586 | if vertex not in self.adjacency_list: 587 | self.adjacency_list[vertex] = [] 588 | 589 | def add_edge(self, vertex1, vertex2): 590 | if vertex1 in self.adjacency_list and vertex2 in self.adjacency_list: 591 | self.adjacency_list[vertex1].append(vertex2) 592 | self.adjacency_list[vertex2].append(vertex1) 593 | 594 | def display(self): 595 | for vertex, edges in self.adjacency_list.items(): 596 | print(f"{vertex}: {edges}") 597 | 598 | 599 | # implement Depth First Search (DFS) algorithm & Breadth First Search (BFS) algorithm 600 | 601 | def dfs(graph, start): 602 | visited = set() 603 | result = [] 604 | 605 | def _dfs(v): 606 | if v not in visited: 607 | visited.add(v) 608 | result.append(v) 609 | for neighbor in graph.get(v, []): 610 | _dfs(neighbor) 611 | 612 | _dfs(start) 613 | return result 614 | 615 | def bfs(graph, start): 616 | visited = set([start]) 617 | queue = [start] 618 | result = [] 619 | 620 | while queue: 621 | vertex = queue.pop(0) 622 | result.append(vertex) 623 | for neighbor in graph.get(vertex, []): 624 | if neighbor not in visited: 625 | visited.add(neighbor) 626 | queue.append(neighbor) 627 | 628 | return result 629 | 630 | 631 | # Longest Substring Without Repeating Characters 632 | 633 | def length_of_longest_substring(s: str) -> int: 634 | start = max_length = 0 635 | used_chars = {} 636 | 637 | for i, char in enumerate(s): 638 | if char in used_chars: 639 | start = max(start, used_chars[char] + 1) 640 | used_chars[char] = i 641 | max_length = max(max_length, i - start + 1) 642 | 643 | return max_length 644 | 645 | # Test the function 646 | print(length_of_longest_substring("abcabcbb")) 647 | 648 | 649 | # same above code with different function name 650 | # Longest Substring Without Repeating Characters 651 | 652 | def longest_unique_substring(s): 653 | char_set = set() # To store unique characters in the window 654 | left = 0 655 | max_length = 0 656 | 657 | for right in range(len(s)): 658 | while s[right] in char_set: # If duplicate found, shrink the window 659 | char_set.remove(s[left]) 660 | left += 1 661 | char_set.add(s[right]) # Add current character to the set 662 | max_length = max(max_length, right - left + 1) # Update the max length 663 | 664 | return max_length 665 | 666 | # Testing the function 667 | print(longest_unique_substring("abcabcbb")) 668 | 669 | 670 | # String Compression 671 | 672 | def compress_string(s): 673 | compressed = [] # To store compressed parts 674 | count = 1 # Count of consecutive characters 675 | 676 | for i in range(1, len(s)): 677 | if s[i] == s[i-1]: # If current character matches previous 678 | count += 1 679 | else: 680 | compressed.append(s[i-1] + str(count)) # Append character and count 681 | count = 1 # Reset the count 682 | compressed.append(s[-1] + str(count)) # Append the last character and count 683 | 684 | compressed_string = ''.join(compressed) 685 | return compressed_string if len(compressed_string) < len(s) else s 686 | 687 | # Testing the function 688 | print(compress_string("aaabbccc")) 689 | print(compress_string("abc")) 690 | 691 | 692 | # find the maximum single sell profit 693 | 694 | def buy_sell_stock_prices(stock_prices): 695 | current_buy = stock_prices[0] 696 | global_sell = stock_prices[1] 697 | global_profit = global_sell - current_buy 698 | 699 | for i in range(1, len(stock_prices)): 700 | current_profit = stock_prices[i] - current_buy 701 | 702 | if current_profit > global_profit: 703 | global_profit = current_profit 704 | global_sell = stock_prices[i] 705 | 706 | if current_buy > stock_prices[i]: 707 | current_buy = stock_prices[i] 708 | 709 | return global_sell - global_profit, global_sell 710 | 711 | stock_prices_1 = [10,9,16,17,19,23] 712 | buy_sell_stock_prices(stock_prices_1) 713 | # (9, 23) 714 | 715 | 716 | stock_prices_2 = [8, 6, 5, 4, 3, 2, 1] 717 | buy_sell_stock_prices(stock_prices_2) 718 | # (6, 5) 719 | 720 | 721 | # adding the inheritance 722 | 723 | class Animal: 724 | def __init__(self, species: str) -> None: 725 | self.species = species 726 | 727 | def make_sound(self) -> str: 728 | return "Some generic sound" 729 | 730 | class Dog(Animal): 731 | def __init__(self, name: str, age: int) -> None: 732 | super().__init__("Dog") 733 | self.name = name 734 | self.age = age 735 | 736 | def make_sound(self) -> str: 737 | return f"{self.name} says Woof!" 738 | 739 | class Cat(Animal): 740 | def __init__(self, name: str, age: int) -> None: 741 | super().__init__("Cat") 742 | self.name = name 743 | self.age = age 744 | 745 | def make_sound(self) -> str: 746 | return f"{self.name} says Meow!" 747 | 748 | # Usage 749 | my_dog = Dog("Buddy", 3) 750 | my_cat = Cat("Whiskers", 2) 751 | print(my_dog.species) # Output: Dog 752 | print(my_dog.make_sound()) # Output: Buddy says Woof! 753 | print(my_cat.species) # Output: Cat 754 | print(my_cat.make_sound()) # Output: Whiskers says Meow! 755 | 756 | 757 | # Abstract Factory Pattern with Multiple Inheritance 758 | 759 | from abc import ABC, abstractmethod 760 | 761 | class Engine(ABC): 762 | @abstractmethod 763 | def create_engine(self): 764 | pass 765 | 766 | class Body(ABC): 767 | @abstractmethod 768 | def create_body(self): 769 | pass 770 | 771 | class LuxuryEngine(Engine): 772 | def create_engine(self): 773 | return "Luxury V8 Engine" 774 | 775 | class SportsEngine(Engine): 776 | def create_engine(self): 777 | return "Sports Turbocharged Engine" 778 | 779 | class LuxuryBody(Body): 780 | def create_body(self): 781 | return "Luxury Sedan Body" 782 | 783 | class SportsBody(Body): 784 | def create_body(self): 785 | return "Sports Coupe Body" 786 | 787 | class CarFactory(ABC): 788 | @abstractmethod 789 | def create_engine(self) -> Engine: 790 | pass 791 | 792 | @abstractmethod 793 | def create_body(self) -> Body: 794 | pass 795 | 796 | class LuxuryCarFactory(CarFactory): 797 | def create_engine(self): 798 | return LuxuryEngine() 799 | 800 | def create_body(self): 801 | return LuxuryBody() 802 | 803 | class SportsCarFactory(CarFactory): 804 | def create_engine(self): 805 | return SportsEngine() 806 | 807 | def create_body(self): 808 | return SportsBody() 809 | 810 | def build_car(factory: CarFactory): 811 | engine = factory.create_engine() 812 | body = factory.create_body() 813 | return f"Built Car: {body.create_body()} with {engine.create_engine()}" 814 | 815 | luxury_car = build_car(LuxuryCarFactory()) 816 | sports_car = build_car(SportsCarFactory()) 817 | 818 | print(luxury_car) 819 | print(sports_car) 820 | 821 | 822 | # merge intervals 823 | 824 | def merge_intervals(intervals): 825 | if not intervals: 826 | return [] 827 | 828 | # Sort intervals based on the start time 829 | intervals.sort(key=lambda x: x[0]) 830 | merged = [intervals[0]] 831 | 832 | for current in intervals[1:]: 833 | prev = merged[-1] 834 | if current[0] <= prev[1]: # Overlapping intervals 835 | prev[1] = max(prev[1], current[1]) 836 | else: 837 | merged.append(current) 838 | 839 | return merged 840 | 841 | # Example usage: 842 | intervals = [[1,3],[2,6],[8,10],[15,18]] 843 | print(merge_intervals(intervals)) 844 | 845 | 846 | 847 | # next greater element 848 | 849 | def next_greater_element(arr): 850 | stack = [] 851 | nge = [-1] * len(arr) 852 | 853 | for i in range(len(arr)): 854 | while stack and arr[stack[-1]] < arr[i]: 855 | index = stack.pop() 856 | nge[index] = arr[i] 857 | stack.append(i) 858 | 859 | return nge 860 | 861 | # Example usage: 862 | arr = [4, 5, 2, 25] 863 | print(next_greater_element(arr)) 864 | 865 | 866 | # find duplicate numbers 867 | 868 | def find_duplicate(nums): 869 | # Using Floyd's Tortoise and Hare (Cycle Detection) 870 | slow = fast = nums[0] 871 | 872 | # Phase 1: Finding the intersection point 873 | while True: 874 | slow = nums[slow] 875 | fast = nums[nums[fast]] 876 | if slow == fast: 877 | break 878 | 879 | # Phase 2: Finding the entrance to the cycle 880 | slow = nums[0] 881 | while slow != fast: 882 | slow = nums[slow] 883 | fast = nums[fast] 884 | 885 | return slow 886 | 887 | # Example usage: 888 | nums = [3, 1, 3, 4, 2] 889 | print(find_duplicate(nums)) 890 | 891 | 892 | # Binary Search validation 893 | 894 | class TreeNode: 895 | def __init__(self, val=0, left=None, right=None): 896 | self.val = val 897 | self.left = left 898 | self.right = right 899 | 900 | def is_valid_bst(root, low=float('-inf'), high=float('inf')): 901 | if not root: 902 | return True 903 | if not (low < root.val < high): 904 | return False 905 | return (is_valid_bst(root.left, low, root.val) and 906 | is_valid_bst(root.right, root.val, high)) 907 | 908 | # Example usage: 909 | root = TreeNode(2) 910 | root.left = TreeNode(1) 911 | root.right = TreeNode(3) 912 | print(is_valid_bst(root)) 913 | 914 | 915 | # Longest Substring Without Repeating Characters 916 | 917 | def length_of_longest_substring(s): 918 | char_index = {} 919 | start = max_length = 0 920 | 921 | for index, char in enumerate(s): 922 | if char in char_index and char_index[char] >= start: 923 | start = char_index[char] + 1 924 | else: 925 | max_length = max(max_length, index - start + 1) 926 | char_index[char] = index 927 | 928 | return max_length 929 | 930 | # Example usage: 931 | s = "abcabcbb" 932 | print(length_of_longest_substring(s)) 933 | 934 | # implementing stack using queue 935 | 936 | from collections import deque 937 | 938 | class MyStack: 939 | def __init__(self): 940 | self.queue = deque() 941 | 942 | def push(self, x): 943 | self.queue.append(x) 944 | for _ in range(len(self.queue) - 1): 945 | self.queue.append(self.queue.popleft()) 946 | 947 | def pop(self): 948 | return self.queue.popleft() 949 | 950 | def top(self): 951 | return self.queue[0] 952 | 953 | def empty(self): 954 | return not self.queue 955 | 956 | # Example usage: 957 | stack = MyStack() 958 | stack.push(1) 959 | stack.push(2) 960 | print(stack.top()) # Output: 2 961 | print(stack.pop()) # Output: 2 962 | print(stack.empty()) # Output: False 963 | 964 | 965 | 966 | from typing import List, Self 967 | 968 | Self.left = None 969 | Self.right = None 970 | 971 | def level_order_traversal(root): 972 | if not root: 973 | return [] 974 | result = [] 975 | queue = [root] 976 | while queue: 977 | level = [] 978 | for _ in range(len(queue)): 979 | node = queue.pop(0) 980 | level.append(node.val) 981 | if node.left: 982 | queue.append(node.left) 983 | if node.right: 984 | queue.append(node.right) 985 | result.append(level) 986 | return result 987 | 988 | # sum of the elements 989 | 990 | def sum_of_elements(numbers): 991 | total = 0 992 | for i in numbers: 993 | total += i 994 | return total 995 | 996 | num = [] 997 | try: 998 | n = int(input("Enter the number of elements: ")) 999 | for i in range(n): 1000 | num.append(int(input(f"Enter number {i+1}: "))) 1001 | print("The sum of the numbers is:", sum_of_elements(num)) 1002 | except ValueError: 1003 | print("Please enter valid integers only.") 1004 | -------------------------------------------------------------------------------- /DSA_Bunch.py: -------------------------------------------------------------------------------- 1 | # Binary Search Tree (BST) Insertion 2 | 3 | class TreeNode: 4 | def __init__(self, val=0): 5 | self.val = val 6 | self.left = None 7 | self.right = None 8 | 9 | def insert_into_bst(root, val): 10 | if root is None: 11 | return TreeNode(val) 12 | if val < root.val: 13 | root.left = insert_into_bst(root.left, val) 14 | else: 15 | root.right = insert_into_bst(root.right, val) 16 | return root 17 | 18 | # Example usage: 19 | # Constructing the following BST: 20 | # 4 21 | # / \ 22 | # 2 7 23 | # / \ 24 | # 1 3 25 | 26 | root = TreeNode(4) 27 | insert_into_bst(root, 2) 28 | insert_into_bst(root, 7) 29 | insert_into_bst(root, 1) 30 | insert_into_bst(root, 3) 31 | 32 | 33 | # Combination Sum 34 | 35 | def combination_sum(candidates, target): 36 | result = [] 37 | candidates.sort() 38 | find_combinations(candidates, target, 0, [], result) 39 | return result 40 | 41 | def find_combinations(candidates, target, index, path, result): 42 | if target == 0: 43 | result.append(path) 44 | return 45 | for i in range(index, len(candidates)): 46 | if candidates[i] > target: 47 | break 48 | find_combinations(candidates, target - candidates[i], i, path + [candidates[i]], result) 49 | 50 | # Example usage: 51 | candidates = [2,3,6,7] 52 | target = 7 53 | print(combination_sum(candidates, target)) # Output: [[2,2,3],[7]] 54 | 55 | 56 | 57 | # Binary Tree Level Order Traversal 58 | 59 | class TreeNode: 60 | def __init__(self, val=0): 61 | self.val = val 62 | self.left = None 63 | self.right = None 64 | 65 | def level_order_traversal(root): 66 | if not root: 67 | return [] 68 | result = [] 69 | queue = [root] 70 | while queue: 71 | level = [] 72 | for _ in range(len(queue)): 73 | node = queue.pop(0) 74 | level.append(node.val) 75 | if node.left: 76 | queue.append(node.left) 77 | if node.right: 78 | queue.append(node.right) 79 | result.append(level) 80 | return result 81 | 82 | # Example usage: 83 | # Constructing the following binary tree: 84 | # 3 85 | # / \ 86 | # 9 20 87 | # / \ 88 | # 15 7 89 | 90 | root = TreeNode(3) 91 | root.left = TreeNode(9) 92 | root.right = TreeNode(20) 93 | root.right.left = TreeNode(15) 94 | root.right.right = TreeNode(7) 95 | 96 | print(level_order_traversal(root)) # Output: [[3],[9,20],[15,7]] 97 | 98 | 99 | # Course Schedule (Detecting Cycles in a Directed Graph) 100 | 101 | from collections import defaultdict, deque 102 | 103 | def can_finish(numCourses, prerequisites): 104 | in_degree = [0] * numCourses 105 | adjacency_list = defaultdict(list) 106 | for dest, src in prerequisites: 107 | adjacency_list[src].append(dest) 108 | in_degree[dest] += 1 109 | queue = deque([i for i in range(numCourses) if in_degree[i] == 0]) 110 | visited = 0 111 | while queue: 112 | node = queue.popleft() 113 | visited += 1 114 | for neighbor in adjacency_list[node]: 115 | in_degree[neighbor] -= 1 116 | if in_degree[neighbor] == 0: 117 | queue.append(neighbor) 118 | return visited == numCourses 119 | 120 | # Example usage: 121 | numCourses = 2 122 | prerequisites = [[1,0]] 123 | print(can_finish(numCourses, prerequisites)) # Output: True 124 | 125 | 126 | 127 | # Evaluate Reverse Polish Notation 128 | 129 | def eval_rpn(tokens): 130 | stack = [] 131 | for token in tokens: 132 | if token in {"+", "-", "*", "/"}: 133 | b = stack.pop() 134 | a = stack.pop() 135 | if token == "+": 136 | stack.append(a + b) 137 | elif token == "-": 138 | stack.append(a - b) 139 | elif token == "*": 140 | stack.append(a * b) 141 | else: # token == "/" 142 | stack.append(int(a / b)) # Truncate towards zero 143 | else: 144 | stack.append(int(token)) 145 | return stack[0] 146 | 147 | # Example usage: 148 | tokens = ["2", "1", "+", "3", "*"] 149 | print(eval_rpn(tokens)) # Output: 9 150 | 151 | 152 | 153 | # Longest Increasing Subsequence 154 | 155 | def length_of_lis(nums): 156 | if not nums: 157 | return 0 158 | dp = [1] * len(nums) 159 | for i in range(1, len(nums)): 160 | for j in range(i): 161 | if nums[i] > nums[j]: 162 | dp[i] = max(dp[i], dp[j] + 1) 163 | return max(dp) 164 | 165 | # Example usage: 166 | nums = [10,9,2,5,3,7,101,18] 167 | print(length_of_lis(nums)) # Output: 4 168 | 169 | 170 | # Serialize and Deserialize Binary Tree 171 | 172 | class TreeNode: 173 | def __init__(self, val=0, left=None, right=None): 174 | self.val = val 175 | self.left = left 176 | self.right = right 177 | 178 | class Codec: 179 | def serialize(self, root): 180 | def helper(node): 181 | if not node: 182 | vals.append("#") 183 | else: 184 | vals.append(str(node.val)) 185 | helper(node.left) 186 | helper(node.right) 187 | vals = [] 188 | helper(root) 189 | return ' '.join(vals) 190 | 191 | def deserialize(self, data): 192 | def helper(): 193 | val = next(vals) 194 | if val == "#": 195 | return None 196 | node = TreeNode(int(val)) 197 | node.left = helper() 198 | node.right = helper() 199 | return node 200 | vals = iter(data.split()) 201 | return helper() 202 | 203 | # Example usage: 204 | # Constructing the following tree: 205 | # 1 206 | # / \ 207 | # 2 3 208 | # / \ 209 | # 4 5 210 | 211 | root = TreeNode(1) 212 | root.left = TreeNode(2) 213 | root.right = TreeNode(3) 214 | root.right.left = TreeNode(4) 215 | root.right.right = TreeNode(5) 216 | 217 | codec = Codec() 218 | data = codec.serialize(root) 219 | print(data) # Output: "1 2 # # 3 4 # # 5 # #" 220 | new_root = codec.deserialize(data) 221 | print(codec.serialize(new_root) == data) # Output: True 222 | 223 | 224 | # Maximum Subarray 225 | 226 | def max_subarray(nums): 227 | max_sum = float('-inf') 228 | current_sum = 0 229 | for num in nums: 230 | current_sum = max(num, current_sum + num) 231 | max_sum = max(max_sum, current_sum) 232 | return max_sum 233 | 234 | # Example usage: 235 | nums = [-2,1,-3,4,-1,2,1,-5,4] 236 | print(max_subarray(nums)) # Output: 6 237 | 238 | 239 | # median of two sorted arrays 240 | 241 | def findMedianSortedArrays(nums1, nums2): 242 | def kthElement(arr1, arr2, k): 243 | if not arr1: 244 | return arr2[k] 245 | if not arr2: 246 | return arr1[k] 247 | idx1, idx2 = len(arr1) // 2, len(arr2) // 2 248 | median1, median2 = arr1[idx1], arr2[idx2] 249 | if idx1 + idx2 < k: 250 | if median1 > median2: 251 | return kthElement(arr1, arr2[idx2 + 1:], k - idx2 - 1) 252 | else: 253 | return kthElement(arr1[idx1 + 1:], arr2, k - idx1 - 1) 254 | else: 255 | if median1 > median2: 256 | return kthElement(arr1[:idx1], arr2, k) 257 | else: 258 | return kthElement(arr1, arr2[:idx2], k) 259 | 260 | total_len = len(nums1) + len(nums2) 261 | if total_len % 2 == 1: 262 | return kthElement(nums1, nums2, total_len // 2) 263 | else: 264 | return (kthElement(nums1, nums2, total_len // 2 - 1) + 265 | kthElement(nums1, nums2, total_len // 2)) / 2.0 266 | 267 | # Example usage: 268 | nums1 = [1, 3] 269 | nums2 = [2] 270 | print(findMedianSortedArrays(nums1, nums2)) # Output: 2.0 271 | 272 | # Trapping Rain Water 273 | 274 | def trap(height): 275 | if not height: 276 | return 0 277 | left, right = 0, len(height) - 1 278 | left_max, right_max = height[left], height[right] 279 | water = 0 280 | while left < right: 281 | if left_max < right_max: 282 | left += 1 283 | left_max = max(left_max, height[left]) 284 | water += left_max - height[left] 285 | else: 286 | right -= 1 287 | right_max = max(right_max, height[right]) 288 | water += right_max - height[right] 289 | return water 290 | 291 | # Example usage: 292 | height = [0,1,0,2,1,0,1,3,2,1,2,1] 293 | print(trap(height)) # Output: 6 294 | 295 | 296 | # N-Queens Problem (Backtracking) 297 | 298 | def solveNQueens(n): 299 | def backtrack(row, diagonals, anti_diagonals, cols, state): 300 | if row == n: 301 | board.append(["".join(row) for row in state]) 302 | return 303 | for col in range(n): 304 | curr_diag = row - col 305 | curr_anti_diag = row + col 306 | if (col in cols or curr_diag in diagonals or 307 | curr_anti_diag in anti_diagonals): 308 | continue 309 | cols.add(col) 310 | diagonals.add(curr_diag) 311 | anti_diagonals.add(curr_anti_diag) 312 | state[row][col] = 'Q' 313 | backtrack(row + 1, diagonals, anti_diagonals, cols, state) 314 | cols.remove(col) 315 | diagonals.remove(curr_diag) 316 | anti_diagonals.remove(curr_anti_diag) 317 | state[row][col] = '.' 318 | 319 | board = [] 320 | empty_board = [['.'] * n for _ in range(n)] 321 | backtrack(0, set(), set(), set(), empty_board) 322 | return board 323 | 324 | # Example usage: 325 | n = 4 326 | for solution in solveNQueens(n): 327 | for row in solution: 328 | print(row) 329 | print() 330 | -------------------------------------------------------------------------------- /LeetCode_Questions/997_Squarred_a_sorted_array.py: -------------------------------------------------------------------------------- 1 | class Solutions: # Class name 2 | def sort(self, nums : list[int]) -> list[int]: # Function name with input and output 3 | return sorted([i*i for i in nums]) # Return the sorted list of squared elements of the input list 4 | # Time Complexity is O(nlogn) because of sorting 5 | # Space Complexity is O(n) because of the list comprehension 6 | nums = [1, 0, -4, 7, -10] # Input list 7 | solution = Solutions() # Class object 8 | print(solution.sort(nums)) # [0, 1, 16, 49, 100] -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Study Python Repository 🚀🐍 2 | 3 | Welcome to the **Study Python** repository! This is a comprehensive collection of Python programs, covering everything from beginner to advanced levels, Data Structures and Algorithms **(DSA)**, LeetCode practice solutions, and a structured **30 Days of Python** challenge. Whether you're just starting or refining your skills, this repo has something for everyone. Let's code more! 💻🔥 4 | 5 | ## 📌 Repository Contents 6 | 7 | ### 1️⃣ Beginner to Advanced Python Programs 8 | - Python Basics (Variables, Data Types, Operators, Loops, Functions) 9 | - Object-Oriented Programming (OOP) in Python 10 | - File Handling & Exception Handling 11 | - Python Modules & Packages 12 | - Advanced Python Concepts (Decorators, Generators, Multithreading, etc.) 13 | 14 | ### 2️⃣ Data Structures & Algorithms (DSA) 🏗️ 15 | - The DSA's for your Life 16 | 17 | ### 3️⃣ 30 Days of Python Challenge 📅 18 | A well-structured roadmap to master Python in **30 days**: 19 | - Day 1-10: Python Basics & Core Concepts 20 | - Day 11-20: Intermediate Python (OOP, File Handling, Libraries) 21 | - Day 21-30: Advanced Python & Real-World Projects 22 | 23 | ### 4️⃣ LeetCode & Coding Practice Solutions 🔥 24 | - Solutions to popular **LeetCode** problems 25 | - Coding challenges from **HackerRank, CodeSignal, CodeChef, and more is upcoming** 26 | - Optimized & well-commented solutions 27 | 28 | ## 🛠️ How to Use This Repository 29 | 1. Clone the repository: 30 | ```sh 31 | git clone https://github.com/AzaamAhmed/StudyPython.git 32 | ``` 33 | 2. Navigate into the directory: 34 | ```sh 35 | cd StudyPython 36 | ``` 37 | 3. Explore different sections & start coding! 38 | 4. Run Python scripts: 39 | ```sh 40 | python filename.py 41 | ``` 42 | 43 | ## 📖 Resources & References 44 | - **Books:** Python Crash Course, Automate the Boring Stuff with Python 45 | - **Courses:** Udemy, Coursera, YouTube tutorials 46 | - **Platforms:** LeetCode, HackerRank, GeeksforGeeks, CodeSignal 47 | 48 | ## 👨‍💻 Contributing 49 | Feel free to contribute by adding new Python programs, optimizing existing solutions, or fixing bugs. Open a pull request with detailed explanations! 50 | 51 | ## ⭐ Show Some Love 52 | If you find this repository useful, **give it a star ⭐** and share it with fellow learners! 53 | 54 | Happy Coding! 🚀🐍 55 | -------------------------------------------------------------------------------- /Top_20_Python_Coding_Interview_QuestionSimple/P01.py: -------------------------------------------------------------------------------- 1 | # Write a program to print the given number is odd or even. 2 | 3 | # 1st we want to check whether its odd or even by iusing the modulus operator 4 | # its give the remainder of the devision 5 | # and if its 0 then its even otherwise its odd 6 | 7 | def odd_even_checker(num): 8 | if num % 2 == 0: 9 | print(f"{num} is Even") 10 | else: 11 | print(f"{num} is Odd") 12 | 13 | num = int(input("Enter the Number: ")) 14 | odd_even_checker(num) -------------------------------------------------------------------------------- /Top_20_Python_Coding_Interview_QuestionSimple/P02.py: -------------------------------------------------------------------------------- 1 | # This program checks if a number is positive, negative, or zero. 2 | # It prompts the user to enter a number and then checks its value. 3 | # If the number is less than 0, it is negative. 4 | # If the number is greater than 0, it is positive. 5 | # If the number is equal to 0, it is zero. 6 | 7 | def check_pos_or_neg(num): 8 | if num < 0: 9 | print(f"{num} is negative") 10 | elif num > 0: 11 | print(f"{num} is positive") 12 | else: 13 | print(f"{num} is zero") 14 | 15 | num = int(input("Enter your wished number:")) 16 | check_pos_or_neg(num) -------------------------------------------------------------------------------- /Top_20_Python_Coding_Interview_QuestionSimple/P03.py: -------------------------------------------------------------------------------- 1 | # Write a program to find the sum of two numbers. 2 | 3 | def sumoftwo(a, b): 4 | return a + b 5 | 6 | num1 = int(input("Enter the first number: ")) 7 | num2 = int(input("Enter the second number: ")) 8 | print("The Sum of the Numbers is: ", sumoftwo(num1, num2)) -------------------------------------------------------------------------------- /Top_20_Python_Coding_Interview_QuestionSimple/P04.py: -------------------------------------------------------------------------------- 1 | # Write a program to find if the given number is prime or not. 2 | 3 | 4 | def checkPrime(num): # Function to check if a number is prime 5 | if num <= 1: # 0 and 1 are not prime numbers 6 | print(f"{num} is not Prime") # 0 and 1 are not prime numbers 7 | return # Exit the function 8 | 9 | for i in range(2, num): # Check for factors from 2 to num-1 10 | if num % i == 0: # If num is divisible by i 11 | print(f"{num} is not Prime") # num is not prime 12 | return # Exit the function 13 | # If no factors found, num is prime 14 | if num > 1: # Check if num is greater than 1 15 | for i in range(2, int(num**0.5) + 1): # Check for factors from 2 to sqrt(num) 16 | if num % i == 0: # If num is divisible by i 17 | print(f"{num} is not Prime") # num is not prime 18 | return # Exit the function 19 | else: # If no factors found, num is prime 20 | print(f"{num} is Prime") # num is prime # num is not prime 21 | return # Exit the function 22 | 23 | 24 | num = int(input("Enter the Number: ")) 25 | checkPrime(num) 26 | 27 | #OR 28 | 29 | num = int(input("Enter a number: ")) 30 | if num > 1 and all(num % i != 0 for i in range(2, int(num**0.5) + 1)): 31 | print(f"{num} is Prime") 32 | else: 33 | print(f"{num} is Not Prime") 34 | print("Prime") 35 | 36 | #OR 37 | 38 | def is_prime(num): # Function to check if a number is prime 39 | if num <= 1: # 0 and 1 are not prime numbers 40 | return False # Return False for non-prime numbers 41 | for i in range(2, int(num**0.5) + 1): # Check for factors from 2 to sqrt(num) 42 | if num % i == 0: # If num is divisible by i 43 | return False # Return False for non-prime numbers 44 | return True # Return True for prime numbers 45 | num = int(input("Enter a number: ")) # Input a number to check if it's prime 46 | if is_prime(num): # Check if num is prime 47 | print(f"{num} is Prime") # Print that num is prime 48 | else: 49 | print(f"{num} is Not Prime") # Print that num is not prime 50 | 51 | -------------------------------------------------------------------------------- /Top_20_Python_Coding_Interview_QuestionSimple/P05.py: -------------------------------------------------------------------------------- 1 | # Write a program to check if the given number is palindrome or not. 2 | 3 | num = input("Enter a number: ") 4 | 5 | if num == num[::-1]: 6 | print(f"{num} is a palindrome.") 7 | else: 8 | print(f"{num} is not a palindrome.") 9 | 10 | #OR 11 | def is_palindrome(num): 12 | return str(num) == str(num)[::-1] 13 | num = int(input("Enter a number: ")) 14 | if is_palindrome(num): 15 | print(f"{num} is a palindrome.") 16 | else: 17 | print(f"{num} is not a palindrome.") 18 | 19 | -------------------------------------------------------------------------------- /Top_20_Python_Coding_Interview_QuestionSimple/P06.py: -------------------------------------------------------------------------------- 1 | # Write a program to check if the given number is Armstrong or not. 2 | 3 | # An Armstrong number is one where the sum of its digits, each raised to the power of the number of digits, equals the number itself. 4 | # For example, 153 is an Armstrong number because 1^3 + 5^3 + 3^3 = 153. 5 | # 6 | # Armstrong numbers are also known as narcissistic numbers or pluperfect digital invariants. 7 | # 8 | # Example: 153, 370, 371, 407 9 | 10 | def is_armstrong(num): 11 | num_str = str(num) 12 | num_digits = len(num_str) 13 | sum_of_powers = sum(int(digit) ** num_digits for digit in num_str) 14 | return num == sum_of_powers 15 | 16 | num = int(input("Enter a number: ")) 17 | 18 | if is_armstrong(num): 19 | print(f"{num} is an Armstrong number.") 20 | else: 21 | print(f"{num} is not an Armstrong number.") 22 | -------------------------------------------------------------------------------- /Top_20_Python_Coding_Interview_QuestionSimple/P07.py: -------------------------------------------------------------------------------- 1 | # Write a program to check if the given strings are anagram or not. 2 | def check(s1, s2): 3 | 4 | if sorted(s1) == sorted(s2): 5 | print("The strings are anagrams.") 6 | else: 7 | print("The strings aren't anagrams.") 8 | 9 | 10 | s1 = input("Enter string1: ") 11 | # input1: "listen" 12 | s2 = input("Enter string2: ") 13 | # input2: "silent" 14 | check(s1, s2) 15 | # Output: the strings are anagrams. 16 | -------------------------------------------------------------------------------- /Top_20_Python_Coding_Interview_QuestionSimple/P08.py: -------------------------------------------------------------------------------- 1 | # Write a program to find a maximum of two numbers. 2 | def maximum(a, b): 3 | 4 | if a >= b: 5 | return a 6 | else: 7 | return b 8 | 9 | 10 | a = int(input("Enter a number: ")) 11 | # input1: 2 12 | b = int(input("Enter a number: ")) 13 | # input2: 4 14 | print(maximum(a, b)) 15 | # output: 4 16 | -------------------------------------------------------------------------------- /Top_20_Python_Coding_Interview_QuestionSimple/P09.py: -------------------------------------------------------------------------------- 1 | # Write a program to find a minimum of two numbers. 2 | def minimum(a, b): 3 | 4 | if a <= b: 5 | return a 6 | else: 7 | return b 8 | 9 | 10 | a = int(input("Enter a number: ")) 11 | # input1: 2 12 | b = int(input("Enter a number: ")) 13 | # input2: 4 14 | print(minimum(a, b)) 15 | # output: 2 16 | -------------------------------------------------------------------------------- /Top_20_Python_Coding_Interview_QuestionSimple/P10.py: -------------------------------------------------------------------------------- 1 | # Write a program to find a maximum of three numbers. 2 | def maximum(a, b, c): 3 | 4 | if (a >= b) and (a >= c): 5 | largest = a 6 | 7 | elif (b >= a) and (b >= c): 8 | largest = b 9 | else: 10 | largest = c 11 | 12 | return largest 13 | 14 | 15 | a = int(input("Enter a number: ")) 16 | # Input1: 10 17 | b = int(input("Enter a number: ")) 18 | # Input2: 14 19 | c = int(input("Enter a number: ")) 20 | # Input3: 12 21 | print(maximum(a, b, c)) 22 | # Output: 14 -------------------------------------------------------------------------------- /Top_20_Python_Coding_Interview_QuestionSimple/P11.py: -------------------------------------------------------------------------------- 1 | # Write a program to find a minimum of three numbers. 2 | a = int(input("Enter first number : ")) 3 | # 12 4 | b = int(input("Enter second number : ")) 5 | # 14 6 | c = int(input("Enter third number : ")) 7 | # 11 8 | smallest = 0 9 | if a < b and a < c: 10 | smallest = a 11 | if b < a and b < c: 12 | smallest = b 13 | if c < a and c < b: 14 | smallest = c 15 | print(smallest, "is the smallest of three numbers.") 16 | # 11 is the smallest of three numbers. 17 | -------------------------------------------------------------------------------- /Top_20_Python_Coding_Interview_QuestionSimple/P12.py: -------------------------------------------------------------------------------- 1 | # Write a program to find a factorial of a number. 2 | 3 | def factorial_Loop(num): 4 | temp = num 5 | if num==0: 6 | print("Factorial is 1") 7 | elif num < 0: 8 | print("Factorial Not Exist") 9 | else: 10 | for i in range(1,num): 11 | temp = temp*i 12 | print(f"Factorial of {num} is {temp}") 13 | 14 | def factorial_recursion(num): 15 | if num==0: 16 | return 1 17 | elif num < 0: 18 | print("Factorial Not Exist") 19 | else: 20 | return num*factorial_recursion(num-1) 21 | 22 | 23 | 24 | 25 | num = int(input("Enter Your Number : ")) 26 | factorial_Loop(num) 27 | print(f"Factorial of {num} is {factorial_recursion(num)}") 28 | 29 | 30 | -------------------------------------------------------------------------------- /Top_20_Python_Coding_Interview_QuestionSimple/P13.py: -------------------------------------------------------------------------------- 1 | # Write a program to find a fibonacci of a number. 2 | 3 | def fibonacciSeries(num): 4 | a = 0 5 | b = 1 6 | for i in range(0,num): 7 | print(a) 8 | sum = a+b 9 | a = b 10 | b = sum 11 | 12 | num = int(input("Enter Number of Term : ")) 13 | fibonacciSeries(num) -------------------------------------------------------------------------------- /Top_20_Python_Coding_Interview_QuestionSimple/P14.py: -------------------------------------------------------------------------------- 1 | # Write a program to find GCD of two numbers. 2 | 3 | def gcd(a,b): 4 | if a==0: 5 | return b 6 | if b==0: 7 | return a 8 | if a==b: 9 | return a 10 | if (a > b): 11 | return gcd(a-b, b) 12 | return gcd(a, b-a) 13 | 14 | a = 98 15 | b = 56 16 | print(f"GCD of {a} & {b} : {gcd(a,b)}") 17 | -------------------------------------------------------------------------------- /Top_20_Python_Coding_Interview_QuestionSimple/P15.py: -------------------------------------------------------------------------------- 1 | # Write a program to print the following pattern. 2 | # * 3 | # * * 4 | # -> * * * 5 | # * * * * 6 | # * * * * * 7 | 8 | def leftpyramid(): 9 | for i in range(0,5): 10 | print("\n") 11 | for j in range(0,i+1): 12 | print("*",end=' ') 13 | leftpyramid() -------------------------------------------------------------------------------- /Top_20_Python_Coding_Interview_QuestionSimple/P16.py: -------------------------------------------------------------------------------- 1 | # Write a program to print the following pattern. 2 | # * 3 | # * * 4 | # * * * 5 | # * * * * 6 | # * * * * * 7 | 8 | def pyramid(): 9 | k = 5-1 10 | for i in range(0,5): 11 | for j in range(0,k): 12 | print(end=" ") 13 | k = k - 1 14 | for j in range(0,i+1): 15 | print("* ",end="") 16 | print("\r") # you can use print("\n") also 17 | 18 | pyramid() -------------------------------------------------------------------------------- /Top_20_Python_Coding_Interview_QuestionSimple/P17.py: -------------------------------------------------------------------------------- 1 | # Write a program to print the following pattern. 2 | # 1 3 | # 1 2 4 | # 1 2 3 5 | # 1 2 3 4 6 | # 1 2 3 4 5 7 | 8 | def left_number_pyramid(): 9 | for i in range(1,5+1): 10 | print("\r") 11 | for j in range(1,i+1): 12 | print(j,end=' ') 13 | left_number_pyramid() -------------------------------------------------------------------------------- /Top_20_Python_Coding_Interview_QuestionSimple/P18.py: -------------------------------------------------------------------------------- 1 | # Write a program to print the following pattern. 2 | # 1 3 | # 2 3 4 | # 4 5 6 5 | # 7 8 9 10 6 | # 11 12 13 14 15 7 | 8 | def left_num_pyramid2(): 9 | temp = 1 10 | for i in range(0,6): 11 | print("\r") 12 | for j in range(1,i+1): 13 | print(temp,end=' ') 14 | temp = temp + 1 15 | left_num_pyramid2() -------------------------------------------------------------------------------- /Top_20_Python_Coding_Interview_QuestionSimple/P19.py: -------------------------------------------------------------------------------- 1 | # Write a program to print the following pattern. 2 | # A 3 | # B B 4 | # C C C 5 | # D D D D 6 | 7 | def left_abc_pyramid(): 8 | numA = 65 9 | for i in range(0,4): 10 | print("\r") 11 | for j in range(0,i+1): 12 | temp = chr(numA) 13 | print(temp,end=' ') 14 | numA = numA + 1 15 | left_abc_pyramid() -------------------------------------------------------------------------------- /Top_20_Python_Coding_Interview_QuestionSimple/P20.py: -------------------------------------------------------------------------------- 1 | # Write a program to print the following pattern. 2 | # A 3 | # B C 4 | # D E F 5 | # G H I J 6 | 7 | def left_abc_pyramid2(): 8 | numA = 65 9 | for i in range(0,4): 10 | print("\r") 11 | for j in range(0,i+1): 12 | temp = chr(numA) 13 | print(temp,end=' ') 14 | numA = numA + 1 15 | left_abc_pyramid2() -------------------------------------------------------------------------------- /fruits.txt: -------------------------------------------------------------------------------- 1 | Banana 2 | Mango 3 | Banana 4 | Mango 5 | Banana 6 | Mango 7 | Hello 8 | Azaam 9 | Areeb 10 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AzaamAhmed/StudyPython/b973907cf419d24d1de35043bc4274c7f72f7120/main.py -------------------------------------------------------------------------------- /new.py: -------------------------------------------------------------------------------- 1 | name = "Azaam" 2 | print("Hello Dear " + name + "!") 3 | 4 | """ a = input("Enter number : ") 5 | print(int(a)*10) """ 6 | 7 | """ mark = int(input()) 8 | if(mark>35): 9 | print("Pass") 10 | else: 11 | print("Fail") """ 12 | 13 | 14 | """ score = int(input("Score : ")) 15 | if (score < 35): 16 | print("Poor Student") 17 | elif (score > 35 and score < 70): 18 | print("Average Student") 19 | else: 20 | print("Good Student") """ 21 | 22 | """ 23 | for i in "APPLE": 24 | print(i) 25 | 26 | for i in range (5): 27 | print(i) """ 28 | 29 | 30 | """ for i in range (1,11): 31 | if(i%2 == 0): 32 | print(i) 33 | 34 | ec = 0 35 | oc = 0 36 | for i in range (1,84): 37 | if(i%2 == 0): 38 | ec = ec + 1 39 | else: 40 | oc = oc + 1 41 | print(ec) 42 | print(oc) 43 | 44 | for i in range (1,5): 45 | print() 46 | for j in range (1,i+1): 47 | print(j,end="") """ 48 | 49 | 50 | """ sname = "Azaam" 51 | spassword = "1234" 52 | 53 | uname = input("Enter Username : ") 54 | password = input("Enter Password : ") 55 | 56 | def validate(): 57 | if( sname == uname and spassword == password): 58 | print("Login Successful") 59 | else: 60 | print("Enter the user credential correctly") 61 | 62 | validate() """ 63 | 64 | """ 65 | class student: 66 | def __init__(self): 67 | self.name = "Azaam" 68 | self.regno = "18095" 69 | def display(self): 70 | print("Name: ", self.name) 71 | print("Reg No: ", self.regno) 72 | 73 | s1=student() 74 | print(s1.name) 75 | print(s1.regno) 76 | s1.display() 77 | """ 78 | 79 | 80 | """ class dad(): 81 | def phone(self): 82 | print("Dad's Phone...") 83 | 84 | class mom(): 85 | def sweet (self): 86 | print("Mom's sweet...") 87 | 88 | class son(dad,mom): 89 | def laptop(self): 90 | print("Son's Laptop...") 91 | 92 | ram=son() 93 | ram.phone() 94 | ram.sweet() """ 95 | 96 | """ class emp(): 97 | def __init__(self,name,salary): 98 | self.name = name 99 | self.salary = salary 100 | 101 | class Mangr(emp): 102 | def __init__(self,dept): 103 | self.dept = dept 104 | 105 | def display(self): 106 | print(self.name, self.salary, self.dept) 107 | 108 | m1 = Mangr("CSE") 109 | m1.display() """ 110 | 111 | """ 112 | f = open("fruits.txt", "a") 113 | f.write("Hello\n") 114 | f.write("Azaam\n") 115 | 116 | f = open("fruits.txt", "r+") 117 | print(f.read()) 118 | """ 119 | 120 | 121 | """ 122 | class computer: 123 | 124 | def __init__(self, cpu, ram): 125 | self.cpu = cpu 126 | self.ram = ram 127 | 128 | def config(self): 129 | print("Config is :", self.cpu, self.ram) 130 | 131 | com1 = computer('i5', 16) 132 | com2 = computer('Ryzen', 8) 133 | 134 | # computer.config(com1) 135 | # computer.config(com2) 136 | 137 | com1.config() 138 | com2.config() 139 | """ 140 | 141 | """ 142 | class computer: ##size of the object declared by number of variables and size of each variables 143 | 144 | def __init__(self): 145 | self.name = "Azaam" 146 | self.age = 23 147 | 148 | def update(self): 149 | self.age = 30 150 | 151 | def compare(self,other): 152 | if self.age == other.age: 153 | return True 154 | else: 155 | return False 156 | 157 | 158 | c1 = computer() ##size of the object allocated by construtor 159 | c2 = computer() 160 | 161 | c1.name = "Fasreen" 162 | c1.age = 22 ##if the both lines are delleted function became true 163 | 164 | if c1.compare(c2): 165 | print("They are same") 166 | else: 167 | print("They are not same") 168 | 169 | print(c1.name) 170 | print(c1.age) 171 | 172 | print(c2.name) 173 | print(c2.age) 174 | """ 175 | 176 | """ 177 | class car: 178 | 179 | wheels = 4 ##class variable 180 | 181 | def __init__(self): 182 | self.mil = 10 ##instance variable 183 | self.com = "Audi" ##instance variable 184 | 185 | c1 = car() 186 | c2 = car() 187 | 188 | car.wheels = 5 189 | 190 | c2.com = "BMW" 191 | c1.mil = 8 192 | print(c1.com, c1.mil, c1.wheels) 193 | print(c2.com, c2.mil, c2.wheels) 194 | 195 | """ 196 | """ 197 | class A: 198 | def show(self): 199 | print("in Show A") 200 | 201 | class B(A): 202 | pass 203 | 204 | a1 = B() 205 | a1.show() """ 206 | 207 | class Nokia: 208 | company = "Nokia India" 209 | website = "www.nokia-india.com" 210 | 211 | def contact_details(self): 212 | print("Address : Cherry Road, Salem") 213 | 214 | class Nokia1100(Nokia): 215 | def __init__(self): 216 | self.name = "Nokia 1100" 217 | self.year = 1998 218 | 219 | def product_details(self): 220 | print("Name : ", self.name) 221 | print("Year : ", self.year) 222 | print("Company : ", self.company) 223 | print("Website : ", self.website) 224 | 225 | 226 | mobile = Nokia1100() 227 | mobile.product_details() 228 | mobile.contact_details() -------------------------------------------------------------------------------- /passwordmanager.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, request, jsonify, session # type: ignore 2 | from werkzeug.security import generate_password_hash, check_password_hash # type: ignore 3 | from cryptography.fernet import Fernet # type: ignore 4 | import sqlite3 5 | import re, os, time 6 | from flask_limiter import Limiter # type: ignore 7 | from flask_limiter.util import get_remote_address # type: ignore 8 | 9 | # Generate encryption key (store securely) 10 | if not os.path.exists("key.key"): 11 | with open("key.key", "wb") as key_file: 12 | key_file.write(Fernet.generate_key()) 13 | 14 | def load_key(): 15 | with open("key.key", "rb") as key_file: 16 | return key_file.read() 17 | 18 | encryption_key = load_key() 19 | cipher_suite = Fernet(encryption_key) 20 | 21 | app = Flask(__name__) 22 | app.secret_key = os.urandom(24) # Secure session 23 | limiter = Limiter(get_remote_address, app=app, default_limits=["5 per minute"]) # Brute-force protection 24 | 25 | # Database setup 26 | def init_db(): 27 | conn = sqlite3.connect("password_manager.db") 28 | cursor = conn.cursor() 29 | cursor.execute('''CREATE TABLE IF NOT EXISTS users ( 30 | id INTEGER PRIMARY KEY, 31 | username TEXT UNIQUE, 32 | password_hash TEXT)''') 33 | cursor.execute('''CREATE TABLE IF NOT EXISTS passwords ( 34 | id INTEGER PRIMARY KEY, 35 | user_id INTEGER, 36 | site TEXT, 37 | encrypted_password TEXT, 38 | FOREIGN KEY(user_id) REFERENCES users(id))''') 39 | conn.commit() 40 | conn.close() 41 | 42 | init_db() 43 | 44 | # Password Validation 45 | def validate_password(password): 46 | if len(password) < 12: 47 | return "Password must be at least 12 characters long" 48 | if not re.search("[A-Z]", password): 49 | return "Password must contain an uppercase letter" 50 | if not re.search("[a-z]", password): 51 | return "Password must contain a lowercase letter" 52 | if not re.search("[0-9]", password): 53 | return "Password must contain a number" 54 | if not re.search("[@$!%*?&]", password): 55 | return "Password must contain a special character" 56 | return None 57 | 58 | @app.route("/register", methods=["POST"]) 59 | def register(): 60 | data = request.json 61 | username = data["username"] 62 | password = data["password"] 63 | 64 | validation_error = validate_password(password) 65 | if validation_error: 66 | return jsonify({"error": validation_error}), 400 67 | 68 | password_hash = generate_password_hash(password) 69 | 70 | conn = sqlite3.connect("password_manager.db") 71 | cursor = conn.cursor() 72 | try: 73 | cursor.execute("INSERT INTO users (username, password_hash) VALUES (?, ?)", (username, password_hash)) 74 | conn.commit() 75 | except sqlite3.IntegrityError: 76 | return jsonify({"error": "Username already exists"}), 400 77 | finally: 78 | conn.close() 79 | 80 | return jsonify({"message": "User registered successfully"}) 81 | 82 | @app.route("/login", methods=["POST"]) 83 | @limiter.limit("5 per minute") 84 | def login(): 85 | data = request.json 86 | username = data["username"] 87 | password = data["password"] 88 | 89 | conn = sqlite3.connect("password_manager.db") 90 | cursor = conn.cursor() 91 | cursor.execute("SELECT id, password_hash FROM users WHERE username = ?", (username,)) 92 | user = cursor.fetchone() 93 | conn.close() 94 | 95 | if not user or not check_password_hash(user[1], password): 96 | return jsonify({"error": "Invalid username or password"}), 401 97 | 98 | session["user_id"] = user[0] 99 | session["last_active"] = time.time() 100 | return jsonify({"message": "Login successful"}) 101 | 102 | @app.route("/store", methods=["POST"]) 103 | def store_password(): 104 | if "user_id" not in session: 105 | return jsonify({"error": "Unauthorized"}), 401 106 | 107 | data = request.json 108 | site = data["site"] 109 | password = data["password"] 110 | encrypted_password = cipher_suite.encrypt(password.encode()).decode() 111 | 112 | conn = sqlite3.connect("password_manager.db") 113 | cursor = conn.cursor() 114 | cursor.execute("INSERT INTO passwords (user_id, site, encrypted_password) VALUES (?, ?, ?)", (session["user_id"], site, encrypted_password)) 115 | conn.commit() 116 | conn.close() 117 | 118 | return jsonify({"message": "Password stored securely"}) 119 | 120 | @app.route("/retrieve", methods=["GET"]) 121 | def retrieve_passwords(): 122 | if "user_id" not in session: 123 | return jsonify({"error": "Unauthorized"}), 401 124 | 125 | conn = sqlite3.connect("password_manager.db") 126 | cursor = conn.cursor() 127 | cursor.execute("SELECT site, encrypted_password FROM passwords WHERE user_id = ?", (session["user_id"],)) 128 | records = cursor.fetchall() 129 | conn.close() 130 | 131 | passwords = [{"site": r[0], "password": cipher_suite.decrypt(r[1].encode()).decode()} for r in records] 132 | return jsonify({"passwords": passwords}) 133 | 134 | @app.route("/logout", methods=["POST"]) 135 | def logout(): 136 | session.clear() 137 | return jsonify({"message": "Logged out successfully"}) 138 | 139 | if __name__ == "__main__": 140 | app.run(debug=True) 141 | -------------------------------------------------------------------------------- /travelGPT.py: -------------------------------------------------------------------------------- 1 | print("Welcome to the TravelGPT 3.0. Lets plan an adventure") 2 | try: 3 | enter = int(input("1 - Start, 2 - quit: ")) 4 | except ValueError: 5 | print("Invalid input. Exiting.") 6 | enter = 2 7 | 8 | while enter == 1: 9 | destination = input("Do you have a destination in mind : ").lower() 10 | if destination == "yes": 11 | print("let's get started") 12 | transport = input("How do you want to travel? (car, bus, train, plane) : ").lower() 13 | if transport == "plane": 14 | class_type = input("What class do you want to fly? (economy, business, first) : ").lower() 15 | if class_type == "economy": 16 | print("You have chosen economy class. Enjoy your flight!") 17 | elif class_type == "business": 18 | print("You have chosen business class. Enjoy your flight!") 19 | elif class_type == "first": 20 | print("You have chosen first class. Enjoy your flight!") 21 | else: 22 | print("Invalid class type. Please choose economy, business, or first.") 23 | elif transport == "train": 24 | class_type = input("What class do you want to travel? (sleeper, AC, general) : ").lower() 25 | if class_type == "sleeper": 26 | print("You have chosen sleeper class. Enjoy your journey!") 27 | elif class_type == "ac": 28 | print("You have chosen AC class. Enjoy your journey!") 29 | elif class_type == "general": 30 | print("You have chosen general class. Enjoy your journey!") 31 | else: 32 | print("Invalid class type. Please choose sleeper, AC, or general.") 33 | elif transport == "car": 34 | print("You have chosen to travel by car. Enjoy your road trip!") 35 | elif transport == "bus": 36 | print("You have chosen to travel by bus. Enjoy your journey!") 37 | else: 38 | print("Invalid transport mode. Please choose car, bus, train, or plane.") 39 | elif destination == "no": 40 | print("No worries! Maybe next time.") 41 | else: 42 | print("Invalid input. Please enter 'yes' or 'no'.") 43 | try: 44 | enter = int(input("1 - Start, 2 - quit: ")) 45 | except ValueError: 46 | print("Invalid input. Exiting.") 47 | enter = 2 48 | 49 | print("Thank you for using TravelGPT 3.0. Have a great day!") --------------------------------------------------------------------------------