Programming Articles

Page 509 of 2547

How to read text files using LINECACHE in Python

Kiran P
Kiran P
Updated on 25-Mar-2026 659 Views

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

How to compare files in Python

Kiran P
Kiran P
Updated on 25-Mar-2026 9K+ Views

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

How to scrape through Media Files in Python?

Kiran P
Kiran P
Updated on 25-Mar-2026 225 Views

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

Program to find start indices of all anagrams of a string S in T in Python

Arnab Chakraborty
Arnab Chakraborty
Updated on 25-Mar-2026 362 Views

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

How to select the largest of each group in Python Pandas DataFrame?

Kiran P
Kiran P
Updated on 25-Mar-2026 743 Views

When analyzing data, you often need to find the row with the largest value in each group. This tutorial shows how to select the most popular movie for each year from a movies dataset using Python Pandas. Preparing the Dataset Let's start by loading a movies dataset and examining its structure ? import pandas as pd import numpy as np # Load movies dataset movies = pd.read_csv("https://raw.githubusercontent.com/sasankac/TestDataSet/master/movies_data.csv") # Display sample rows print("Sample data:") print(movies.sample(n=3)) Sample data: budget id original_language original_title popularity ...

Read More

Program to find numbers represented as linked lists in Python

Arnab Chakraborty
Arnab Chakraborty
Updated on 25-Mar-2026 214 Views

Suppose we have two singly linked lists L1 and L2, each representing a number with least significant digits first. We need to find their sum as a linked list. For example, if L1 = [5, 6, 4] represents 465 and L2 = [2, 4, 8] represents 842, their sum is 1307, which should be returned as [7, 0, 3, 1]. Algorithm To solve this problem, we follow these steps ? Initialize carry = 0 and create a dummy result node Traverse both lists simultaneously while either list has nodes or carry exists For each position, ...

Read More

How to unpack using star expression in Python?

Kiran P
Kiran P
Updated on 25-Mar-2026 2K+ Views

Python's star expression (*) allows you to unpack sequences without knowing their exact length in advance. This solves the limitation of traditional unpacking where you must match the number of variables to sequence elements. The Problem with Traditional Unpacking When unpacking sequences, you must know the exact number of elements ? random_numbers = [0, 1, 5, 9, 17, 12, 7, 10, 3, 2] random_numbers_descending = sorted(random_numbers, reverse=True) print(f"Sorted numbers: {random_numbers_descending}") # This will cause an error - too many values to unpack try: largest, second_largest = random_numbers_descending except ValueError as e: ...

Read More

Program to find number of subsequences with i, j and k number of x, y, z letters in Python

Arnab Chakraborty
Arnab Chakraborty
Updated on 25-Mar-2026 227 Views

When working with string subsequences, we often need to count specific patterns. This problem asks us to find the number of subsequences that contain i number of "x" characters, followed by j number of "y" characters, and then k number of "z" characters, where i, j, k ≥ 1. For example, with the string "xxyz", we can form subsequences like "xyz" (twice) and "xxyz" (once), giving us a total of 3 valid subsequences. Algorithm Approach We use dynamic programming to track the number of valid subsequences ending with each character ? x := count of ...

Read More

How to perform Calculations with Dictionaries in Python?

Kiran P
Kiran P
Updated on 25-Mar-2026 2K+ Views

Dictionaries in Python store key-value pairs, but performing calculations like finding minimum, maximum, or sorting requires special techniques since dictionaries don't have a natural ordering. Let's explore different approaches using tennis player data. Creating Sample Data We'll create a dictionary with tennis players and their Grand Slam titles ? player_titles = { 'Federer': 20, 'Nadal': 20, 'Djokovic': 17, 'Murray': 3, 'Thiem': 1, 'Zverev': 0 } print(player_titles) {'Federer': 20, ...

Read More

How to compare two DataFrames in Python Pandas with missing values

Kiran P
Kiran P
Updated on 25-Mar-2026 2K+ Views

When working with DataFrames containing missing values, comparing data becomes challenging because NumPy's NaN values don't behave like regular values. Understanding how to properly compare DataFrames with missing data is essential for data analysis tasks. Understanding NaN Behavior NumPy NaN values have unique mathematical properties that differ from Python's None object ? import pandas as pd import numpy as np # Python None Object compared against self print(f"Python None == None: {None == None}") # Numpy nan compared against self print(f"np.nan == np.nan: {np.nan == np.nan}") # Is nan greater than numbers? print(f"np.nan ...

Read More
Showing 5081–5090 of 25,466 articles
« Prev 1 507 508 509 510 511 2547 Next »
Advertisements