Data Structures and Algorithms

Data Structures and Algorithms (DSA) form the backbone of computer science. Mastering them is crucial for efficient programming and problem-solving. Python provides built-in support and libraries to implement a variety of data structures and algorithms easily.

Key Topics Covered

10 Examples

# Example 1: Using a stack
stack = []
stack.append(1)
stack.append(2)
print(stack.pop())

# Example 2: Queue with collections
from collections import deque
queue = deque([1, 2, 3])
queue.popleft()

# Example 3: Binary search
import bisect
arr = [1, 3, 5, 7]
print(bisect.bisect_left(arr, 5))

# Example 4: Bubble sort
arr = [5, 2, 1, 4]
for i in range(len(arr)):
    for j in range(len(arr) - i - 1):
        if arr[j] > arr[j+1]:
            arr[j], arr[j+1] = arr[j+1], arr[j]

# Example 5: Dictionary lookup
data = {"name": "Alice", "age": 25}
print(data["age"])

# Example 6: DFS on a graph
graph = {0: [1, 2], 1: [2], 2: [3], 3: []}
visited = set()
def dfs(node):
    if node not in visited:
        print(node)
        visited.add(node)
        for neighbor in graph[node]:
            dfs(neighbor)
dfs(0)

# Example 7: Fibonacci with recursion
def fib(n):
    if n <= 1:
        return n
    return fib(n-1) + fib(n-2)
print(fib(5))

# Example 8: Linked list node
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

# Example 9: Heap with heapq
import heapq
heap = [3, 1, 4]
heapq.heapify(heap)
heapq.heappush(heap, 2)
print(heapq.heappop(heap))

# Example 10: Using set for uniqueness
nums = [1, 2, 2, 3]
unique = set(nums)
print(unique)