Author name: Vaibhav Shah

Optimizing Python Data Structures: When to Use deque, defaultdict, and Counter

Deque from collections import deque def sliding_window_max(nums, k): dq = deque() # Stores indices result = [] for i, num in enumerate(nums): # Remove elements not in sliding window if dq and dq[0] < i – k + 1: dq.popleft() # Remove smaller elements (they won’t be needed) while dq and nums[dq[-1]] < num: dq.pop() …

Optimizing Python Data Structures: When to Use deque, defaultdict, and Counter Read More »

Understanding the Global Interpreter Lock (GIL) and How to Bypass It

import time import threading import multiprocessing def cpu_task(n): total = 0 for _ in range(n): total += 1 return total N = 10**7 # Large computation # Using threads (affected by GIL) start = time.time() threads = [threading.Thread(target=cpu_task, args=(N,)) for _ in range(4)] for t in threads: t.start() for t in threads: t.join() print(f”Threads Time: …

Understanding the Global Interpreter Lock (GIL) and How to Bypass It Read More »

Zero-Copy Data Processing in Python with memoryview

# Create a bytearray with some data data = bytearray(b”Hello, World!”) # Create a memoryview on the bytearray view = memoryview(data) # Access the data directly using the memoryview (no copying) print(“Original data:”, view.tobytes()) # Print original data as bytes # Modify the data through the memoryview view[7:12] = b”Python” # Check how the changes …

Zero-Copy Data Processing in Python with memoryview Read More »

How to Use mmap for Fast File I/O Operations in Python

1. Memory-Mapping a File for Reading import mmap # Open file in read mode with open(“large_file.txt”, “r”) as f: # Memory-map the file (read-only mode) with mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as mm: # Read contents as bytes print(mm[:100]) # Read first 100 bytes print(mm.find(b”search_term”)) # Find a term 2.Memory-Mapping a File for Writing import mmap # …

How to Use mmap for Fast File I/O Operations in Python Read More »

Saving key event video clips with OpenCV Python

import cv2 # Open the video capture (0 for the default camera or a video file path) cap = cv2.VideoCapture(0) # Check if the camera is opened successfully if not cap.isOpened(): print(“Error: Could not open camera.”) exit() # Get the frame width and height to define the video codec frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) …

Saving key event video clips with OpenCV Python Read More »

Scroll to Top