Python Algorithms & Data Structures track

Lesson 02 · Part 1: Foundations

Python Input & Output

sys.stdin.readline, sys.stdout.write and EOF handling

Part 1: Foundations4 min readFree lesson

Introduction

In Python, the input() function is convenient to use, but it is very slow when called repeatedly. For problems like Baekjoon 15552 that require reading input more than 100,000 times, using input() can lead to a time limit exceeded error. Using sys.stdin.readline(), the same task can be handled tens of times faster. I/O optimization is independent of the algorithm itself, but it is a crucial skill in competitive programming to save time using Pass/Fail.


Learning Objectives

  1. Be able to explain why sys.stdin.readline() is faster than input().
  2. Be able to write code that handles various input patterns (single values, space-separated, multiple lines, EOF).
  3. Be able to apply output optimization techniques (sys.stdout.write, '\\n'.join()).

Key Concepts

1. input() vs sys.stdin.readline() speed comparison

Method Internal operation Time to process 100,000 lines (approx.) Features
input() Flushes every time, includes prompt handling 25 sec Convenient but slow
sys.stdin.readline() Reads directly from buffer 0.20.5 sec Fast but includes \n
sys.stdin.read() Reads everything at once 0.050.1 sec Fastest, parsing required

Key point: input() triggers a system call every time, whereas sys.stdin.readline() utilizes an internal buffer.

2. Caution with sys.stdin.readline(): newline character (\n)

import sys

line = sys.stdin.readline()   #'42\n' ← Includes \n at the end!
line = sys.stdin.readline().strip()  #'42' ← Correct usage
n = int(sys.stdin.readline())  #When converting with int(), \n is automatically ignored

Most common mistake: Forgetting .strip() when receiving as a string, causing comparison errors.

3. Frequently used input patterns

import sys
input = sys.stdin.readline  #Overwriting input() (most common pattern)

#A single integer
n = int(input())

#Two integers separated by space
a, b = map(int, input().split())

#A line of integer list
arr = list(map(int, input().split()))

#n lines of input
lines = [input().strip() for _ in range(n)]

#Read all at once (for large input)
data = sys.stdin.read().split()  #List of tokens separated by space/newline

4. sys.stdout.write vs print()

Method Time to print 100,000 lines Features
print() 13 seconds Convenient, auto newline, slow
sys.stdout.write() 0.10.5 seconds Fast, need to add \n manually
'\n'.join() + single output 0.050.1 seconds Fastest, collect in a list and output
import sys

#Slow method — repeated calls to print()
for x in results:
    print(x)

#Fast method — print all at once
sys.stdout.write('\n'.join(map(str, results)) + '\n')

#Or
print('\n'.join(map(str, results)))

5. EOF (End of File) handling

When the number of input lines is unknown and you need to read until the end of the file:

import sys

#Method 1: try/except (safest)
try:
    while True:
        line = input()  #Or sys.stdin.readline().strip()
        if not line:
            continue
        #Processing...
except EOFError:
    pass

#Method 2: for line in sys.stdin (Pythonic)
for line in sys.stdin:
    line = line.strip()
    if not line:
        continue
    #Processing...

#Method 3: read all and then parse
data = sys.stdin.read().split()

Examples

Example 1: speed comparison of input() vs readline() (src/01_input_comparison.py)

Measure the speed of both methods directly using mock data.

python src/01_input_comparison.py
[Expected Output]
input() Simulation       : 0.4523 seconds
sys.stdin.readline() Simulation: 0.0321 seconds
sys.stdin.read().split(): 0.0089 seconds

Example 2: competitive programming I/O template (src/02_fast_io_template.py)

Summarize I/O patterns that can be used directly in practice.

python src/02_fast_io_template.py

Example 3: output optimization (src/03_output_optimization.py)

Compare print() vs sys.stdout.write() vs buffered output.

python src/03_output_optimization.py

Example 4: EOF handling (src/04_eof_handling.py)

Show various patterns for reading until EOF.

python src/04_eof_handling.py

Common Mistakes

  1. Not removing \n from sys.stdin.readline()

    #Incorrect code
    s = sys.stdin.readline()  # '42\n'
    if s == '42':  # False! '42\n' != '42'
        ...
    #Correct code
    s = sys.stdin.readline().strip()  # '42'
    
  2. Overwriting input = sys.stdin.readline and missing .strip()

    input = sys.stdin.readline
    n = int(input())     #OK — ignore \n when converting with int()
    s = input().strip()  #OK — strings must be stripped()
    s = input()          #Danger — string contains \n
    
  3. Printing the output line by line with print() — TLE when there are many prints

  • For Baekjoon problem 15552, you need to optimize not only input but also output.
  • Print at once using '\n'.join(map(str, results)).
  1. Index error after sys.stdin.read().split()

    data = sys.stdin.read().split()
    #You need to parse in the order of data[0], data[1], ...
    #Be careful of mistakes in index calculation!
    
  2. Infinite loop without EOF

    #Incorrect code — infinite loop when stdin is a pipe
    while True:
        line = sys.stdin.readline()
        #If line is an empty string (''), it is EOF
        if not line:  #Without this check, it will be an infinite loop!
            break
    

Summary

Situation Recommended Method
When there are many input lines sys.stdin.readline() or sys.stdin.read()
Simple 1–2 line input Using input() is fine
When there are many output lines '\n'.join(map(str, results)) + single print
When you need to read until EOF for line in sys.stdin

Try it yourself

  1. Run src/01_input_comparison.py and check the actual speed difference.
  2. Write boj_15552.py and submit it to Baekjoon.
  3. Find code you've written before where input() is used a lot and try improving it with sys.stdin.readline().

Reference Materials

Example files

The runnable files used in this lesson. Copy them into your own project and experiment.

src/01_input_comparison.pyPython
# =============================================================================
#Filename: 01_input_comparison.py
#Description: Speed comparison of input() vs sys.stdin.readline() (using io.StringIO)
#Time complexity: O(n) — reads n lines
#Space complexity: O(n) — stores the read data
# =============================================================================
#Note: Instead of using actual stdin, a virtual input stream is created with io.StringIO
#to compare the internal parsing speed of the two methods.
# =============================================================================

import sys
import io
import time
import random


def simulate_input_builtin(lines: list) -> list:
    """Reads line by line like input() and converts to an integer.

    The actual input() has additional overhead such as system calls and prompt handling,
    but here we measure the pure parsing speed difference with readline()."""
    result = []
    for line in lines:          #Pre-prepared list of lines
        result.append(int(line.strip()))  #Simulating input() behavior
    return result


def simulate_readline(stream: io.StringIO, n: int) -> list:
    """Reads one line at a time from a stream like sys.stdin.readline()."""
    result = []
    for _ in range(n):
        result.append(int(stream.readline()))  #\n is ignored when converting with int()
    return result


def simulate_read_all(stream: io.StringIO) -> list:
    """Read all at once using sys.stdin.read().split()."""
    return list(map(int, stream.read().split()))


def benchmark_io(n: int = 100_000) -> None:
    """Compare the speed of reading n integers using three different methods."""
    print(f"\n input method speed comparison (n={n:,} integers)")
    print("=" * 55)

    #Generate test data
    random.seed(42)
    numbers = [random.randint(1, 10 ** 9) for _ in range(n)]
    text = '\n'.join(map(str, numbers)) + '\n'
    lines = [str(x) for x in numbers]  #Convert to string beforehand

    # -----------------------------------------------------------------------
    #Method 1: Simulate input() (parse from list of strings)
    # -----------------------------------------------------------------------
    t0 = time.perf_counter()
    result1 = simulate_input_builtin(lines)
    t_input = time.perf_counter() - t0
    print(f"Simulated input()      : {t_input:.4f} seconds")

    # -----------------------------------------------------------------------
    #Method 2: Simulate sys.stdin.readline()
    # -----------------------------------------------------------------------
    stream2 = io.StringIO(text)
    t0 = time.perf_counter()
    result2 = simulate_readline(stream2, n)
    t_readline = time.perf_counter() - t0
    print(f"Simulated sys.stdin.readline(): {t_readline:.4f} seconds")

    # -----------------------------------------------------------------------
    #Method 3: Simulate sys.stdin.read().split()
    # -----------------------------------------------------------------------
    stream3 = io.StringIO(text)
    t0 = time.perf_counter()
    result3 = simulate_read_all(stream3)
    t_read = time.perf_counter() - t0
    print(f"sys.stdin.read().split(): {t_read:.4f} seconds")

    # -----------------------------------------------------------------------
    #Verify results
    # -----------------------------------------------------------------------
    assert result1 == result2 == result3, "The results are different!"
    print("\n results match: OK")

    # -----------------------------------------------------------------------
    #Speed comparison summary
    # -----------------------------------------------------------------------
    baseline = t_read  #Based on read().split()
    if baseline > 0:
        print("Speed Comparison (compared to read().split())")
        print(f"input() simulation:          {t_input/baseline:>6.1f} times slower")
        print(f"readline() simulation:       {t_readline/baseline:>6.1f} times slower")
        print(f"read().split():        {1.0:>6.1f} times (baseline)")

    print("[Conclusion]")
    print("- The more input there is, the more advantageous sys.stdin.read() becomes.")
    print("- In competitive programming, if N > 10,000, use sys.stdin.")


def show_usage_patterns() -> None:
    """Prints the correct input pattern."""
    print("\n" + "=" * 55)
    print("Practical input pattern examples")
    print("=" * 55)

    patterns = [
        ("Single integer",
         "n = int(sys.stdin.readline())"),
        ("Two space-separated integers",
         "a, b = map(int, sys.stdin.readline().split())"),
        ("List of integers",
         "arr = list(map(int, sys.stdin.readline().split()))"),
        ("Overwriting input",
         "input = sys.stdin.readline\nn = int(input())"),
        ("Read all at once",
         "data = sys.stdin.read().split()\nn = int(data[0])"),
    ]

    for name, code in patterns:
        print(f"\n# {name}")
        for line in code.split('\n'):
            print(f"  {line}")


def main():
    print("=" * 55)
    print("Python I/O speed comparison demo")
    print("=" * 55)

    #Demonstrate newline handling in readline()
    print("[readline() \n handling]")
    stream = io.StringIO("hello\nworld\n")
    raw = stream.readline()
    print(f"readline() result: repr={repr(raw)}")
    print(f"After .strip():   {repr(raw.strip())}")
    print(f"int() conversion:      {int('42\n')} (\n automatically ignored)")

    #Benchmark execution
    benchmark_io(n=100_000)
    show_usage_patterns()


if __name__ == "__main__":
    main()
src/02_fast_io_template.pyPython
# =============================================================================
#Filename: 02_fast_io_template.py
#Description: Collection of fast I/O patterns often used in competitive programming
#Time Complexity: O(n) for each pattern
#Space Complexity: O(n) — proportional to the size of input data
# =============================================================================
#Usage:
#This file can be executed directly or used as a reference template when writing Baekjoon code.
#Demonstrates by creating virtual input with io.StringIO instead of the actual stdin.
# =============================================================================

import sys
import io


# ===========================================================================
#Pattern 1: Replace input() with sys.stdin.readline
#Most commonly used pattern — minimal changes to existing input() code
# ===========================================================================
def pattern1_override_input(fake_stdin: str) -> None:
    """input = sys.stdin.readline pattern demonstration."""
    original_stdin = sys.stdin
    sys.stdin = io.StringIO(fake_stdin)

    #Actual Baekjoon code start point -------------------------------------------------
    input = sys.stdin.readline  #Replace input() with readline

    n = int(input())                         #A single integer
    a, b = map(int, input().split())         #Two integers separated by space
    arr = list(map(int, input().split()))    #List of integers
    s = input().strip()                      #String (strip is essential!)
    # -------------------------------------------------------------------------

    print(f"[Pattern 1] n={n}, a={a}, b={b}, arr={arr}, s='{s}'")
    sys.stdin = original_stdin


# ===========================================================================
#Pattern 2: Read all input at once using sys.stdin.read() and parse
#Fastest method for large input
# ===========================================================================
def pattern2_read_all(fake_stdin: str) -> None:
    """Demonstration of the sys.stdin.read().split() pattern."""
    original_stdin = sys.stdin
    sys.stdin = io.StringIO(fake_stdin)

    #Actual Baekjoon code start point -------------------------------------------------
    data = sys.stdin.read().split()  #All tokens as a list
    idx = 0

    n = int(data[idx]); idx += 1
    arr = [int(data[idx + i]) for i in range(n)]
    idx += n
    # -------------------------------------------------------------------------

    print(f"[Pattern 2] n={n}, arr={arr}")
    sys.stdin = original_stdin


# ===========================================================================
#Pattern 3: Multiple line input — list comprehension
# ===========================================================================
def pattern3_multiline(fake_stdin: str, n: int) -> None:
    """Demonstration of a pattern for receiving multiple line input as a list."""
    original_stdin = sys.stdin
    sys.stdin = io.StringIO(fake_stdin)
    input_fn = sys.stdin.readline

    #Read n lines of [row, column] pairs
    edges = [tuple(map(int, input_fn().split())) for _ in range(n)]
    print(f"[Pattern 3] edges={edges}")
    sys.stdin = original_stdin


# ===========================================================================
#Pattern 4: Read until EOF
# ===========================================================================
def pattern4_eof(fake_stdin: str) -> None:
    """Demonstration of a pattern that reads input until EOF."""
    original_stdin = sys.stdin
    sys.stdin = io.StringIO(fake_stdin)

    results = []
    #for line in sys.stdin — automatically ends at EOF
    for line in sys.stdin:
        line = line.strip()
        if not line:          #Ignore empty lines
            continue
        a, b = map(int, line.split())
        results.append(a + b)

    print(f"[Pattern 4] Result: {results}")
    sys.stdin = original_stdin


# ===========================================================================
#Pattern 5: 2D array input (graph, matrix)
# ===========================================================================
def pattern5_2d_array(fake_stdin: str, rows: int) -> None:
    """A pattern demonstration for quickly inputting a 2D array."""
    original_stdin = sys.stdin
    sys.stdin = io.StringIO(fake_stdin)
    input_fn = sys.stdin.readline

    #Read at once using nested list comprehension
    grid = [list(map(int, input_fn().split())) for _ in range(rows)]
    print(f"[Pattern 5] grid=")
    for row in grid:
        print(f"  {row}")
    sys.stdin = original_stdin


def main():
    print("=" * 55)
    print("Demonstration of fast I/O pattern collection")
    print("=" * 55)

    #Demonstration of Pattern 1
    pattern1_override_input("5\n3 7\n1 2 3 4 5\nhello\n")

    #Demonstration of Pattern 2
    pattern2_read_all("4\n10 20 30 40\n")

    #Demonstration of Pattern 3
    pattern3_multiline("1 2\n3 4\n5 6\n", n=3)

    #Demonstration of Pattern 4 (EOF handling)
    pattern4_eof("1 2\n3 4\n5 6\n7 8\n")

    #Demonstration of Pattern 5 (2D array)
    pattern5_2d_array("1 2 3\n4 5 6\n7 8 9\n", rows=3)

    print("\n" + "=" * 55)
    print("Baekjoon code basic template")
    print("=" * 55)
    template = """import sys
input = sys.stdin.readline  # Fast input

def solve():
    n = int(input())
    arr = list(map(int, input().split()))
    # ... solution code ...
    print("Answer")

if __name__ == "__main__":
    solve()"""
    print(template)


if __name__ == "__main__":
    main()
src/03_output_optimization.pyPython
# =============================================================================
#Filename: 03_output_optimization.py
#Description: Comparing print() vs sys.stdout.write vs buffered output speed
#Time Complexity: O(n) — n outputs
#Space Complexity: O(n) — storing results in a list for buffer method
# =============================================================================

import sys
import io
import time
import random


def method_print_loop(numbers: list) -> float:
    """A way to repeatedly call print(). It's slow, but the code is simple."""
    buf = io.StringIO()
    original = sys.stdout
    sys.stdout = buf

    t0 = time.perf_counter()
    for x in numbers:       #n print() calls
        print(x)
    elapsed = time.perf_counter() - t0

    sys.stdout = original
    return elapsed


def method_stdout_write_loop(numbers: list) -> float:
    """How to repeatedly call sys.stdout.write()."""
    buf = io.StringIO()
    original = sys.stdout
    sys.stdout = buf

    t0 = time.perf_counter()
    write = sys.stdout.write
    for x in numbers:       #n write() calls
        write(str(x))
        write('\n')
    elapsed = time.perf_counter() - t0

    sys.stdout = original
    return elapsed


def method_join_single_write(numbers: list) -> float:
    """After joining all results with join(), print once. This is the fastest method."""
    buf = io.StringIO()
    original = sys.stdout
    sys.stdout = buf

    t0 = time.perf_counter()
    #Generate a single string using list comprehension + join → 1 write
    result = '\n'.join(map(str, numbers)) + '\n'
    sys.stdout.write(result)
    elapsed = time.perf_counter() - t0

    sys.stdout = original
    return elapsed


def method_list_append_join(numbers: list) -> float:
    """Collect the content to be printed in a list and print it all at once at the end."""
    buf = io.StringIO()
    original = sys.stdout
    sys.stdout = buf

    t0 = time.perf_counter()
    output = []             #Acts as an output buffer
    for x in numbers:
        output.append(str(x))  #Convert to string and store
    sys.stdout.write('\n'.join(output) + '\n')  #Single output
    elapsed = time.perf_counter() - t0

    sys.stdout = original
    return elapsed


def benchmark_output(n: int = 100_000) -> None:
    """Compares the speed of four output methods."""
    random.seed(42)
    numbers = [random.randint(1, 10 ** 9) for _ in range(n)]

    print(f"Speed comparison of \n output methods (outputting n={n:,} integers)")
    print("=" * 55)

    t1 = method_print_loop(numbers)
    t2 = method_stdout_write_loop(numbers)
    t3 = method_join_single_write(numbers)
    t4 = method_list_append_join(numbers)

    baseline = t3 if t3 > 0 else 1e-9
    print(f"Repeated print():        {t1:.4f}s  ({t1/baseline:>5.1f}x)")
    print(f"Repeated write():        {t2:.4f}s  ({t2/baseline:>5.1f}x)")
    print(f"join + single write:     {t3:.4f}s  ({1.0:>5.1f}x, baseline)")
    print(f"list.append + join:      {t4:.4f}s  ({t4/baseline:>5.1f}x)")

    print("[Conclusion]")
    print("Outputting at once is faster than calling print() n times.")
    print("The '\n'.join(map(str, results)) pattern is recommended.")


def show_output_patterns() -> None:
    """Shows the actual output pattern."""
    print("\n" + "=" * 55)
    print("Example output patterns")
    print("=" * 55)

    results = [10, 20, 30, 40, 50]

    #Pattern 1: Repeated print() (slow)
    print("Pattern 1: Repeating print() (OK when N is small)")
    for x in results:
        print(x)

    #Pattern 2: '
'.join() output at once (recommended)
    print("Pattern 2: join + single output (recommended when N is large)")
    print('\n'.join(map(str, results)))

    #Pattern 3: Direct use of sys.stdout.write
    print("Pattern 3: sys.stdout.write")
    sys.stdout.write('\n'.join(map(str, results)) + '\n')

    #Pattern 4: Using f-strings (complex formatting)
    print("Pattern 4: f-string format output")
    pairs = [(1, 'a'), (2, 'b'), (3, 'c')]
    print('\n'.join(f"Case #{i}: {v}" for i, v in pairs))


def main():
    print("=" * 55)
    print("Output optimization demo")
    print("=" * 55)

    show_output_patterns()
    benchmark_output(n=50_000)


if __name__ == "__main__":
    main()
src/04_eof_handling.pyPython
# =============================================================================
#Filename: 04_eof_handling.py
#Description: Demonstration of various patterns to read until EOF (End of File)
#Time complexity: O(n) — proportional to the number of lines
#Space complexity: O(n) — storing results
# =============================================================================
#EOF problem types:
#- When it says "until the end of input"
#- When the number of lines is not given
#- Baekjoon examples: Problem 10951 A+B-4, Problem 11021 A+B-7
# =============================================================================

import sys
import io


def pattern_try_except(fake_input: str) -> list:
    """Method 1: readline() returns an empty string at EOF.

    readline() returns '\n' for an empty line,
    and '' (empty string) at EOF."""
    original_stdin = sys.stdin
    sys.stdin = io.StringIO(fake_input)

    results = []
    try:
        while True:
            line = sys.stdin.readline()
            if not line:        #readline() returns an empty string at EOF
                break
            line = line.strip()
            if not line:        #Skip empty lines
                continue
            a, b = map(int, line.split())
            results.append(a + b)
    except (EOFError, ValueError):
        pass  #EOF or invalid input → exit quietly

    sys.stdin = original_stdin
    return results


def pattern_for_in_stdin(fake_input: str) -> list:
    """Method 2: for line in sys.stdin pattern.

    This is the most Pythonic way.
    Iterating over the file object directly automatically ends at EOF."""
    original_stdin = sys.stdin
    sys.stdin = io.StringIO(fake_input)

    results = []
    for line in sys.stdin:      #Automatically exit at EOF
        line = line.strip()
        if not line:
            continue
        a, b = map(int, line.split())
        results.append(a + b)

    sys.stdin = original_stdin
    return results


def pattern_read_all_split(fake_input: str) -> list:
    """Method 3: Read all with sys.stdin.read() and then parse.

    Read the input at once into memory and then parse it.
    It is the fastest because there are no repeated system calls."""
    original_stdin = sys.stdin
    sys.stdin = io.StringIO(fake_input)

    data = sys.stdin.read().split()  #Read all and then split by whitespace
    results = []
    i = 0
    while i + 1 < len(data):
        a = int(data[i])
        b = int(data[i + 1])
        results.append(a + b)
        i += 2

    sys.stdin = original_stdin
    return results


def pattern_readline_empty_check(fake_input: str) -> list:
    """Method 4: Detect EOF with the return value of readline().

    readline() returns '' → EOF
    readline() returns '\n' → empty line (not EOF)"""
    original_stdin = sys.stdin
    sys.stdin = io.StringIO(fake_input)

    results = []
    while True:
        line = sys.stdin.readline()
        if line == '':           #EOF detection: empty string
            break
        line = line.strip()
        if not line:             #Skip empty lines (if only '\n')
            continue
        try:
            a, b = map(int, line.split())
            results.append(a + b)
        except ValueError:
            continue             #Ignore incorrect format

    sys.stdin = original_stdin
    return results


def main():
    print("=" * 55)
    print("Demonstrate EOF handling patterns")
    print("=" * 55)

    #Test input (including empty lines)
    test_input = "1 2\n3 4\n\n5 6\n7 8\n"
    expected = [3, 7, 11, 15]  #a+b for each line

    print(f"\nTest input:")
    for line in test_input.rstrip('\n').split('\n'):
        display = repr(line) if line else "'' (empty line)"
        print(f"  {display}")
    print(f"\nExpected result: {expected}")

    #Demonstrate each pattern
    r1 = pattern_try_except(test_input)
    r2 = pattern_for_in_stdin(test_input)
    r3 = pattern_read_all_split(test_input)
    r4 = pattern_readline_empty_check(test_input)

    print(f"\nMethod 1 (readline + empty check): {r1}")
    print(f"Method 2 (for in stdin):           {r2}")
    print(f"Method 3 (read all):               {r3}")
    print(f"Method 4 (readline empty check):   {r4}")

    all_correct = (r1 == r2 == r3 == r4 == expected)
    print(f"\nAll method results match: {all_correct}")

    print("\n" + "=" * 55)
    print("Explanation of readline() EOF behavior")
    print("=" * 55)
    stream = io.StringIO("line1\nline2\n")
    print(f"1st time: repr={repr(stream.readline())}  <- normal line")
    print(f"2nd time: repr={repr(stream.readline())}  <- normal line")
    print(f"3rd time: repr={repr(stream.readline())}  <- EOF! empty string")
    print(f"4th time: repr={repr(stream.readline())}  <- still empty string")

    print("[Conclusion] readline() returns '' → EOF signal")
    print("[Conclusion] readline() returns '\n' → empty line (not EOF)")


if __name__ == "__main__":
    main()

Assignment

Solve the following three problems, and be sure to write using fast I/O with sys.stdin.


Problem 1: Baekjoon 15552 — Fast A+B

Problem Summary

T test cases are given. For each test case, input A and B and output A+B.

Input:
5
1 1
12 34
5 500
40 60
1000 1000

Output:
2
46
505
100
2000

Why is fast I/O necessary?

  • T ≤ 1,000,000 (one million input/output operations)
  • Calling input() one million times takes about 5~10 seconds → Time limit exceeded
  • Using sys.stdin.readline() takes about 0.5~1 second → Passes

Requirements

  1. Use sys.stdin (mandatory)
  2. Gather output in a buffer and print at once (recommended)
  3. Include comments on time complexity and space complexity at the top

Complexity Analysis

Item Value
Time Complexity O(T)
Space Complexity O(T) (output buffer)

Submission Files

boj_15552.py


Problem 2: Baekjoon 11021 — A+B - 7

Problem Summary

T test cases are given. Output each line in Case #x: A+B format.

Input:
5
1 1
12 34
5 500
40 60
1000 1000

Output:
Case #1: 2
Case #2: 46
Case #3: 505
Case #4: 100
Case #5: 2000

Requirements

  1. Use sys.stdin
  2. Print in the Case #x: format using f-string or % format
  3. Collect and process output at once (recommended)

Submission Files

boj_11021.py


Problem 3: Baekjoon 11022 — A+B - 8

Problem Summary

Given T test cases. Print each line in Case #x: A + B = C format.

Input:
5
1 1
12 34
5 500
40 60
1000 1000

Output:
Case #1: 1 + 1 = 2
Case #2: 12 + 34 = 46
Case #3: 5 + 500 = 505
Case #4: 40 + 60 = 100
Case #5: 1000 + 1000 = 2000

Requirements

  1. Use sys.stdin
  2. Formatted output with f-string
  3. Process the output at once

Submission Files

boj_11022.py


Submission Checklist

  • Write time complexity and space complexity comments at the top of each file
  • Use sys.stdin or sys.stdin.readline
  • Use a method that processes output at once
  • Code receives Correct answer in Baekjoon
  • Follow PEP 8 style

Tips

#Template optimized for 15552
import sys
input = sys.stdin.readline

def solve():
    T = int(input())
    output = []
    for _ in range(T):
        a, b = map(int, input().split())
        output.append(str(a + b))
    sys.stdout.write('\n'.join(output) + '\n')

solve()
Show the reference solution

Try the assignment yourself first — comparing your attempt with a working solution is where most of the learning happens.

boj_11021.pyPython
# =============================================================================
#Baekjoon 11021: A+B - 7
#Link: https://www.acmicpc.net/problem/11021
#Time complexity: O(T) — processing T test cases
#Space complexity: O(T) — output buffer
#
#Output format: 'Case #x: A+B' (x is the case number starting from 1)
# =============================================================================

import sys
input = sys.stdin.readline


def solve():
    t = int(input())    #Number of test cases
    output = []

    for case_num in range(1, t + 1):         #Case number: starts from 1
        a, b = map(int, input().split())
        #Formatting with f-string
        output.append(f"Case #{case_num}: {a + b}")

    sys.stdout.write('\n'.join(output) + '\n')


if __name__ == "__main__":
    solve()
boj_11022.pyPython
# =============================================================================
#Baekjoon 11022: A+B - 8
#Link: https://www.acmicpc.net/problem/11022
#Time complexity: O(T) — processing T test cases
#Space complexity: O(T) — output buffer
#
#Output format: 'Case #x: A + B = C' (x is the case number, C = A+B)
# =============================================================================

import sys
input = sys.stdin.readline


def solve():
    t = int(input())    #Number of test cases
    output = []

    for case_num in range(1, t + 1):
        a, b = map(int, input().split())
        #Example format: 'Case #1: 1 + 1 = 2'
        output.append(f"Case #{case_num}: {a} + {b} = {a + b}")

    sys.stdout.write('\n'.join(output) + '\n')


if __name__ == "__main__":
    solve()
boj_15552.pyPython
# =============================================================================
#Baekjoon 15552: Fast A+B
#Link: https://www.acmicpc.net/problem/15552
#Time complexity: O(T) — processing T test cases
#Space complexity: O(T) — store output results in a list
#
#Key point: Because T ≤ 1,000,000, fast I/O is absolutely necessary
#- Use sys.stdin.readline() (using input() causes TLE)
#- Collect outputs in a list and print all at once (repeated calls to print() cause TLE)
# =============================================================================

import sys
input = sys.stdin.readline  #Replace input() — fast input


def solve():
    t = int(input())          #Number of test cases
    output = []               #Output buffer — to print at once

    for _ in range(t):
        a, b = map(int, input().split())  #Read two integers separated by a space
        output.append(str(a + b))         #Convert the result to a string and store it

    #Print at once — much faster than calling print() T times
    sys.stdout.write('\n'.join(output) + '\n')


if __name__ == "__main__":
    solve()

Learn this lesson with a mentor

Work through the Python Algorithms & Data Structures track on your own, or join a guided cohort at our Pitampura campus and online.

Call NowEnroll Now