Data Structures & Algorithms in Python
Data Structures & Algorithms in Python
The 'break' statement terminates the current loop and resumes execution at the next statement following the loop. The 'continue' statement skips the rest of the code inside the loop for the current iteration and jumps to the next iteration of the loop. For example, in a 'for' loop iterating over numbers 1 to 5, using 'break' when a number equals 3 will stop the loop entirely, while 'continue' will skip printing number 3 and continue with 4 and 5 .
Arrays are fixed-size and provide constant-time access to elements using indices, whereas linked lists are dynamic and have variable size, but require linear time to access elements. A singly linked list's node contains data and a reference to the next node, while a doubly linked list's node contains data and references to both next and previous nodes, allowing traversal in both directions .
Hashing is a technique to map data to a fixed size using hash functions, crucial for data retrieval efficiency. Collisions occur when two values hash to the same key. Strategies to handle collisions include open addressing, where subsequent slots are checked, and chaining, where each slot retains a list of elements that hash to the same slot. For instance, with chaining, if keys 3 and 8 both hash to index 0, they are stored in a list at that index .
In Python, a class is a blueprint for creating objects, which are instances of the class. A class defines attributes and methods that its objects will have. For demonstration, you can create a Student class with attributes like name and age, and methods to initialize and display these details. Two student objects can then be created and their details displayed. Example: 'class Student: def __init__(self, name, age): self.name = name; self.age = age; def display(self): print("Name:", self.name, "Age:", self.age)' .
To count the number of words in a string in Python, you can use the split() method on the string, which separates the words based on spaces and returns a list. The length of this list corresponds to the number of words. Example: 'input_string = input("Enter a string: "); word_count = len(input_string.split())' .
Exception handling in Python involves managing errors using 'try', 'except', and optionally 'finally', and 'else' blocks. 'Try' contains the code that might throw an exception, and 'except' captures the error if it occurs. 'Finally' is used for code that should run regardless of whether an exception occurred. For example, using 'try: result = 10 / x except ZeroDivisionError: print("Can't divide by zero")', where 'x' is a variable, handles division by zero errors .
A list in Python is a mutable, ordered sequence of elements. Five operations on lists include: 1) append() which adds an element to the end of the list, e.g., list.append(4); 2) remove() which removes the first occurrence of a value, e.g., list.remove(2); 3) pop() which removes and returns the last item, e.g., list.pop(); 4) insert() which inserts a value at a specified position, e.g., list.insert(2, 'Python'); and 5) sort() which sorts the list in place, e.g., list.sort().
Time complexity reflects the computation time of an algorithm relative to input size, crucial for efficiency. Space complexity indicates the memory usage relative to input size, affecting resource demands. Important to optimize both for performance, time complexity guides on speed, space complexity on memory usage constraints. Balancing them impacts an algorithm's practicality and feasibility in practice .
A BST is created by inserting elements while maintaining the property that left children are smaller and right children larger than the parent node. Inserting 60 first, followed by 56, 40, 34, 70, 80, 50, and 45 results in a specific structure. Deleting node 34 involves removing the node and reconnecting its parent node 40 directly to the node following 34's left subtree, which is 50 in this case .
Binary search divides the list and discards half during each comparison, enabling log(n) efficiency, unlike linear search's O(n), searching element by element. In Python, implement as: 'def binary_search(arr, x): low, high = 0, len(arr) - 1; while low <= high: mid = (high + low) // 2; if arr[mid] < x: low = mid + 1; elif arr[mid] > x: high = mid - 1; else: return mid'. Thus, efficiency stems from halving search domain each step .