A clean and efficient template for Codeforces competitions in Python.
# Run the setup script
./setup.sh
# Or manually create the environment
conda env create -f _environment.ymlconda activate codeforcespython --version # Should show Python 3.11.xpython/
โโโ A.py, B.py, C.py, D.py, E.py, F.py # Solution files for each problem
โโโ main.py # Test runner script
โโโ test.py # Unit test template
โโโ input.txt # Input test cases
โโโ output.txt # Expected output (optional)
โโโ requirements.txt # Python dependencies
โโโ environment.yml # Conda environment config
โโโ setup.sh # Setup script
- Copy test cases to
input.txt - Write your solution in the problem file (e.g.,
A.py) - Run the test:
python main.py A # Test problem A
python main.py B # Test problem BThe test runner automatically compares your output with output.txt and shows pass/fail indicators:
Verification Results:
==================================================
# Got Expected
--------------------------------------------------
1 โ 6 6
2 โ 10 10
3 โ 15 14 <- Red โ for wrong answer
4 โ 0 0
--------------------------------------------------
Failed: 3/4 passed
==================================================
Usage:
python main.py A # Run with auto-verification (default)
python main.py A --no-verify # Run without verificationHow to use:
- Copy sample input to
input.txt - Copy expected output to
output.txt - Run
python main.py A- instantly see which test cases pass or fail
python A.py < input.txtModify and run test.py for quick unit tests:
python test.pyEach problem file (A.py - F.py) follows this structure:
def solve():
"""Main solution function"""
# Read input
n = int(input())
# Your logic here
result = n
# Output result
print(result)
def main():
"""Handle multiple test cases"""
t = int(input())
for _ in range(t):
solve()
if __name__ == "__main__":
main() # Or solve() for single test case# Fast I/O for large inputs
import sys
input = sys.stdin.readline
# Multiple values on one line
a, b, c = map(int, input().split())
# List of integers
arr = list(map(int, input().split()))
# Multiple lines
n = int(input())
data = [input().strip() for _ in range(n)]# Binary search
from bisect import bisect_left, bisect_right
# Sorting with custom key
arr.sort(key=lambda x: (x[0], -x[1]))
# Counter for frequency
from collections import Counter
freq = Counter(arr)
# Default dict
from collections import defaultdict
graph = defaultdict(list)
# Deque for efficient queue operations
from collections import deque
q = deque()import math
# GCD and LCM
from math import gcd
def lcm(a, b):
return abs(a * b) // gcd(a, b)
# Prime checking
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
# Modular arithmetic
MOD = 10**9 + 7
result = (a + b) % MOD- O(n): Linear - usually safe up to n = 10^8
- O(n log n): Sorting - safe up to n = 10^6
- O(nยฒ): Nested loops - safe up to n = 10^4
- O(2^n): Exponential - safe up to n = 20
- โ Forgetting to handle multiple test cases
- โ Not using
strip()when reading strings - โ Integer overflow (Python handles this well!)
- โ Wrong input format (check problem statement carefully)
- โ Printing extra spaces or newlines
# Activate environment
conda activate codeforces
# Deactivate environment
conda deactivate
# Update environment
conda env update -f environment.yml
# Install new package
pip install <package-name>
# Delete environment (if needed)
conda env remove -n codeforces- Read all problems first - identify the easiest ones
- Start with easier problems - build confidence and rating
- Use input.txt for testing - faster than manual input
- Test edge cases:
- Minimum values (n=1, empty arrays)
- Maximum values (constraints)
- Special cases (all same, all different)
- Before submitting:
- Check input/output format
- Test with sample cases
- Check for TLE (time limit)
- Remove debug prints
# Debug print (remove before submission!)
print(f"Debug: n={n}, arr={arr}", file=sys.stderr)
# Assert for validation during development
assert len(arr) == n, "Array length mismatch"
# Timing your code
import time
start = time.time()
# ... your code ...
print(f"Time: {time.time() - start:.3f}s", file=sys.stderr)- Math/Number Theory: GCD, LCM, primes, modular arithmetic
- Greedy: Sorting, optimization
- DP: Memoization, tabulation
- Graph: BFS, DFS, shortest paths
- Data Structures: Arrays, hash maps, heaps
- Strings: Pattern matching, manipulation
- Binary Search: On answer space
- Combinatorics: Permutations, combinations
Good luck in your competition! ๐