Python functions and command-line scripts often need flexible parameter handling. Optional arguments allow you to provide default values when parameters aren't supplied, making your code more user-friendly and robust. Optional Function Arguments In Python functions, you can make arguments optional by providing default values ? def greet(name="World", greeting="Hello"): return f"{greeting}, {name}!" # Using default values print(greet()) # Using one argument print(greet("Alice")) # Using both arguments print(greet("Bob", "Hi")) Hello, World! Hello, Alice! Hi, Bob! Optional Command-Line Arguments with argparse The argparse module handles optional ... Read More
Python's Matplotlib library allows you to combine multiple graphs in a single figure to create comprehensive visualizations. You can use subplots to display different charts vertically or horizontally, and dual axes to overlay different data types on the same plot. Preparing Sample Data First, let's prepare sample data for mobile phone sales across different years ? import matplotlib.pyplot as plt # Sample mobile phone sales data (in millions) mobile_brands = ['iPhone', 'Galaxy', 'Pixel'] # Sales data: (Year, iPhone, Galaxy, Pixel) units_sold = ( ('2016', 12, 8, 6), ... Read More
Checking if a string starts or ends with specific text patterns is a common task in Python programming. The startswith() and endswith() methods provide elegant solutions for pattern matching at string boundaries. Using startswith() Method The startswith() method returns True if the string begins with the specified prefix ? Example text = "Is USA colder than Australia?" print(f"Starts with 'Is': {text.startswith('Is')}") Starts with 'Is': True Example filename = "Hello_world.txt" print(f"Starts with 'Hello': {filename.startswith('Hello')}") Starts with 'Hello': True Example site_url = 'https://www.something.com' ... Read More
Python provides several methods to search for and replace text patterns in strings. For simple literal patterns, use str.replace(). For complex patterns, use the re module with regular expressions. Basic Text Searching Let's start by creating a sample text and exploring basic search methods ? def sample(): yield 'Is' yield 'USA' yield 'Colder' yield 'Than' yield 'Canada?' text = ' '.join(sample()) print(f"Output {text}") Output Is USA Colder Than Canada? ... Read More
A priority queue is a data structure where elements are processed based on their priority rather than insertion order. Python's queue module provides PriorityQueue for thread-safe priority-based processing. Basic FIFO Queue First, let's understand a regular FIFO (First In, First Out) queue where elements are processed in insertion order − import queue fifo = queue.Queue() # Put numbers into queue for i in range(5): fifo.put(i) # Get numbers from queue print("FIFO Output:") while not fifo.empty(): print(fifo.get()) FIFO Output: 0 1 2 3 ... Read More
Memory mapping (MMAP) allows Python to access file data directly through the operating system's virtual memory, bypassing traditional I/O operations. This technique significantly improves file reading performance by eliminating system calls and buffer copying. How MMAP Works MMAP maps file contents directly into memory, treating them as mutable strings or file-like objects. The mmap module supports methods like read(), write(), seek(), and slice operations. Basic File Reading with MMAP Let's create a sample file and demonstrate basic MMAP usage ? import mmap # Create sample text file sample_text = """Lorem ipsum dolor sit ... Read More
The linecache module in Python provides an efficient way to read specific lines from text files. It caches file contents in memory and allows random access to lines by their line number, making it ideal when you need to read multiple lines from the same file repeatedly. Key Features of linecache The linecache module offers several advantages − Memory caching: File contents are parsed and stored in memory Line indexing: Access lines directly by line number (starting from 1) Performance: Avoids repeatedly reading and parsing the same file Creating Test Data First, let's ... Read More
Python's filecmp module provides efficient methods to compare files and directories. It offers three main functions: cmp() for comparing individual files, cmpfiles() for comparing multiple files, and dircmp() for comprehensive directory comparison. Basic File Comparison with cmp() The filecmp.cmp() function compares two files and returns True if they are identical, False otherwise ? import filecmp import os # Create test files with open('file1.txt', 'w') as f: f.write('Hello World') with open('file2.txt', 'w') as f: f.write('Hello World') with open('file3.txt', 'w') as f: f.write('Different ... Read More
Scraping through media files in Python involves extracting data, metadata, or content from various media formats like images, audio, and video files. Python provides several libraries to work with different media types and extract useful information from them. Working with Image Files The PIL (Python Imaging Library) and its modern fork Pillow are commonly used for image processing and metadata extraction. from PIL import Image from PIL.ExifTags import TAGS import os # Create a sample image for demonstration img = Image.new('RGB', (100, 100), color='red') img.save('sample.jpg') # Load and extract basic information image = Image.open('sample.jpg') ... Read More
Suppose we have two strings S and T, we have to find all the start indices of S's anagrams in T. The strings consist of lowercase letters only and the length of both strings S and T will not be larger than 20 and 100. So, if the input is like S = "cab" T = "bcabxabc", then the output will be [0, 1, 5] as the substrings "bca", "cab" and "abc" are anagrams of "cab". Using Sliding Window with Character Count We can solve this using a sliding window approach with character frequency counting ? ... Read More
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Economics & Finance