Python Essentials for Competitive Programming and Algorithm Contests

1. Efficient Input Handling

In competitive programming, reading data efficiently is crucial. Python provides several ways to handle single and multiple lines of input.

# Reading a single string
user_data = input()

# Reading and converting to an integer
base_value = int(input())

# Reading multiple space-separated integers into variables
start, step, end = map(int, input().split())

# Reading a space-separated sequence into a list
data_points = list(map(int, input().split()))

# Reading a fixed number of lines into a list (e.g., 5 lines)
vertical_data = [int(input()) for _ in range(5)]

# Reading a 2D matrix (3x3)
grid = [list(map(int, input().split())) for _ in range(3)]

2. String Transformation and Case Sensitivity

Python strings are immutable, so methods return new string objects rather than modifyign the original.

word = "PythonProgramming"

# Case conversions
print(word.upper())      # PYTHONPROGRAMMING
print(word.lower())      # pythonprogramming
print(word.swapcase())   # pYTHONpROGRAMMING
print(word.capitalize()) # Pythonprogramming

# Joining a list of strings into one
tokens = ["Competitive", "Coding", "2024"]
sentence = "-".join(tokens) # "Competitive-Coding-2024"

3. Lambda Functions and Custom Sorting

Anonymous functions (lambdas) are useful for short-lived logic, especially when used as keys for sorting complex data structures.

# Using map with lambda
numbers = [1, 5, 10]
cubes = list(map(lambda x: x**3, numbers)) # [1, 125, 1000]

# Sorting a list of tuples by the second element
coordinate_pairs = [(5, 20), (10, 5), (1, 15)]
# Sort by the second value in each tuple
coordinate_pairs.sort(key=lambda item: item[1]) 
# Result: [(10, 5), (1, 15), (5, 20)]

4. Base Conversion and ASCII Operations

Hendling different number systems and character codes is a common requirement in algorithmic challenges.

# Converting integers to hex, octal, and binary strings
value = 255
print(hex(value)) # '0xff'
print(oct(value)) # '0o377'
print(bin(value)) # '0b11111111'

# Character to ASCII and vice versa
char_code = ord('A') # 65
character = chr(66)  # 'B'

5. Floating Point Formatting

Precise output formatting is often required for geometry or probability problems.

pi_estimate = 22 / 7
# Formatting to 4 decimal places using f-strings
print(f"{pi_estimate:.4f}") # 3.1429

6. Sorting Mechanisms

Python offers two primary ways to sort: the sorted() function and the .sort() method.

collection = [42, 7, 19, 88, 3]

# sorted() returns a new list, original remains unchanged
new_list = sorted(collection, reverse=True)

# .sort() modifies the list in place
collection.sort() 

7. Essential String Built-in Methods

The str class contains powerful tools for pattern searching and text manipulation.

sample_text = "algorithm-analysis"

# Finding indices
print(sample_text.find("rithm")) # Returns index 4
print(sample_text.find("query")) # Returns -1 if not found

# Counting occurrences
print(sample_text.count("a"))    # 3

# Replacement (first 2 occurrences)
modified = sample_text.replace("-", "_", 1)

# Trimming whitespace or specific characters
raw_str = "###Data###"
clean_str = raw_str.strip("#") # "Data"

# Splitting into a list
path = "usr/local/bin"
parts = path.split("/") # ['usr', 'local', 'bin']

8. List Operations and Element Management

Lists are the most versatile sequences in Python for managing collections of data.

list_a = [10, 20]
list_b = [30, 40]

# Merging lists
combined = list_a + list_b # [10, 20, 30, 40]

# Adding elements
list_a.append(100)       # [10, 20, 100]
list_a.extend([5, 6])    # [10, 20, 100, 5, 6]
list_a.insert(1, 99)     # Inserts 99 at index 1

# Removing elements
list_a.remove(20)        # Removes the first instance of 20
popped_val = list_a.pop() # Removes and returns the last item

Tags: python Competitive Programming String Manipulation Data Structures algorithms

Posted on Thu, 06 Aug 2026 16:30:36 +0000 by jpraj