Online coding assessments: format and Python setup
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Your code passes the sample, then the platform says "wrong answer" or "time limit exceeded" on tests you cannot see. Coding rounds are scored by a program, not a reader, so format, input handling and speed matter as much as the idea.
Anatomy of a coding problem
A judge is the program on a coding platform that runs your code on test cases and compares your output with the expected output. Nobody reads your code at this stage.
Every problem has the same parts: a statement, input and output formats, constraints and samples. Here is a problem in that shape, used through the rest of this lesson.
Order totalsShopLite received n orders today. Print the total sales and the largest order.Input: line 1: n line 2: n integers a1 ... an (order amounts)Output: line 1: total line 2: largest orderConstraints: 1 <= n <= 100000, 1 <= ai <= 1000000000Sample input: Sample output:5 60001200 950 1800 700 1350 1800Hidden test cases are the many inputs you never see, including edge cases and very large inputs. Passing the samples only proves your program works for the samples. The constraints (here 1 ≤ n ≤ 10⁵) tell you how large those hidden inputs can get.
Reading input in Python: input() and sys.stdin
sys.stdin.read().split() reads all the input at once and splits it into words (tokens), which you convert with int(). For 10⁵ numbers or more it is the usual safe choice, because calling input() again and again is slower.
Below, the same problem is solved twice: first with input(), then with sys.stdin.read().split().
Example 1 · Solution with input()
n = int(input())amounts = list(map(int, input().split()))print(sum(amounts))print(max(amounts))6000 1800
What this code does
- Run it and type the sample input (5, then the five order amounts), or pipe it in from a file:
python main.py < input.txt. It prints exactly two lines and nothing else. - The sum can reach 10¹⁴ here, and Python's
inthandles it without any special type.input()is fine for small inputs.
Example 2 · The same solution with sys.stdin
import sys
data = sys.stdin.read().split()n = int(data[0])amounts = list(map(int, data[1:1 + n]))print(sum(amounts))print(max(amounts))6000 1800
What this code does
sys.stdin.read()takes all the input as one string andsplit()cuts it into words, so it does not matter whether the numbers sit on one line or several.data[1:1 + n]takes the n amounts after n.- This version reads 10⁵ or more numbers faster than many
input()calls, which is why it is a common template for coding rounds.
Most platforms run one Python file that reads standard input and prints standard output. Print no prompt and read nothing from files. Python's int has no size limit, so a large total needs no special type.
Check the allowed languages before the test. Many coding rounds accept Python, but some tests or companies allow only certain languages, and the Python version can differ from your laptop's. Read the instructions screen and the language menu, and choose the language before you start writing. Revise: Judge-style input and output with sys.stdin (opens in a new tab)
Printing exactly the expected output
The output format is the part of the problem that says exactly what to print and in what layout. The judge compares your output with the expected one, often character by character or line by line.
Extra text such as a prompt makes a right number wrong. The examples below show outputs with the same numbers, only one of which matches, and a faster way to print many lines.
Example 3 · Extra text makes a right answer wrong
marks = [78, 91, 66]expected = "78 91 66"
with_prompt = "Marks are: 78 91 66"loop = ""for m in marks: loop += str(m) + " " # leaves a space at the endjoined = " ".join(str(m) for m in marks)
print(f"[{with_prompt}] matches: {with_prompt == expected}")print(f"[{loop}] matches: {loop == expected}")print(f"[{joined}] matches: {joined == expected}")[Marks are: 78 91 66] matches: False [78 91 66 ] matches: False [78 91 66] matches: True
What this code does
- The brackets show exactly what was printed. The label and the trailing space both break an exact match, even though the numbers are right.
- Some judges ignore the trailing space, but the label always fails. Print only what the output format asks for.
Example 4 · Fast output with one print
n = 5lines = [f"{i} {i * i}" for i in range(1, n + 1)]print("\n".join(lines))1 1 2 4 3 9 4 16 5 25
What this code does
- Every line is built into one list, and
"\n".join(lines)makes one string thatprintwrites at once. With 10⁵ lines this is much faster than 10⁵ separateprintcalls. i * inever overflows in Python, so no extra type is needed for largei.
Many judges ignore a trailing space or a final newline, but not all, so match the format exactly. For large output, calling print thousands of times can be slow. Collect the lines in a list, join them with "\n".join(...) and print once at the end.
Verdicts: accepted, wrong answer, time limit, errors
A verdict is the judge's result for one test case, such as Accepted, Wrong answer, Time limit exceeded, Runtime error or Compilation error.
The mini judge below runs a buggy and a fixed solution on five hidden-style tests and reports a partial score.
Example 5 · A mini judge: wrong answer on one hidden test
def solve_buggy(text): data = text.split() n = int(data[0]) amounts = data[1:1 + n] # bug: these are still strings return f"{sum(map(int, amounts))}\n{max(amounts)}"
def solve_fixed(text): data = text.split() n = int(data[0]) amounts = list(map(int, data[1:1 + n])) return f"{sum(amounts)}\n{max(amounts)}"
inputs = ["4\n10 20 30 40", "1\n5", "3\n7 7 7", "3\n100 200 300", "5\n1200 950 1800 700 1350"]expected = ["100\n40", "5\n5", "21\n7", "600\n300", "6000\n1800"]
print("Buggy solution:")passed = 0for t, (text, want) in enumerate(zip(inputs, expected), start=1): got = solve_buggy(text) if got == want: passed += 1 print(f"Test {t}: passed") else: print(f"Test {t}: wrong answer (expected largest {want.split()[1]}, got {got.split()[1]})")print(f"Passed {passed} of {len(inputs)} -> partial score {passed * 100 // len(inputs)}%")
fixed = sum(solve_fixed(text) == want for text, want in zip(inputs, expected))print(f"Fixed solution: passed {fixed} of {len(inputs)}")Buggy solution: Test 1: passed Test 2: passed Test 3: passed Test 4: passed Test 5: wrong answer (expected largest 1800, got 950) Passed 4 of 5 -> partial score 80% Fixed solution: passed 5 of 5
What this code does
- The buggy version passes the four tests where every number has the same number of digits, so it looks right. On the last test it compares the text "950" with "1800", and text order puts "950" first: a wrong answer verdict.
- Partial scoring gave 80% even with the bug. Converting with
intfixes it; forgetting that input arrives as text is a common wrong-answer cause in Python rounds.
Common verdicts:
- Accepted: correct output within the time limit.
- Wrong answer: the output differs. Check edge cases, data types and format.
- Time limit exceeded (TLE): too slow. Use a better algorithm or faster input and output.
- Runtime error: the program crashed, for example with
IndexErrororValueError. - Compilation or syntax error: the code could not start, for example a
SyntaxError. Some platforms report this as a runtime error.
Many assessments use partial scoring: marks for each hidden test you pass. A simple solution that passes 6 of 10 tests is worth far more than a clever one that does not run.
Reading constraints to pick the complexity
Constraints are the limits the problem promises for its input, such as 1 ≤ n ≤ 10⁵ and values up to 10⁹. They tell you how fast your solution must be.
A judge runs plain Python at about 10⁶ to 10⁷ simple operations per second, and the time limit is usually 1 to 2 seconds. The example below estimates steps for n = 10⁵.
Example 6 · Estimating steps from the constraints
from math import log2
n = 100_000pairs = n * (n - 1) // 2 # O(n^2): every pairn_log_n = n * log2(n) # O(n log n): sortingops_per_second = 10**7 # rough estimate for plain Python
print(f"n = {n}")print(f"O(n^2) pairs: {pairs} steps, about {pairs / ops_per_second:.1f} s")print(f"O(n log n): {n_log_n:.0f} steps, about {n_log_n / ops_per_second:.3f} s")print(f"O(n): {n} steps, about {n / ops_per_second:.3f} s")n = 100000 O(n^2) pairs: 4999950000 steps, about 500.0 s O(n log n): 1660964 steps, about 0.166 s O(n): 100000 steps, about 0.010 s
What this code does
- Checking every pair of 10⁵ items is about 5 × 10⁹ steps: around 500 seconds at a rough 10⁷ steps per second, far over a 1 to 2 second limit. That is a time limit exceeded verdict.
- Sorting-based O(n log n) needs about 1.7 million steps and O(n) only 10⁵, both inside the limit. Read the constraints first and choose the approach before you type.
Real speed depends on the platform and the code, so treat this as an estimate. For n up to 10⁵, O(n²) means about 10¹⁰ steps, far too slow; O(n log n) or O(n) is needed.
- n ≤ 20: O(2ⁿ) or O(n!) can pass.
- n ≤ 1000 to 2000: O(n²) is usually fine.
- n ≤ 10⁵: O(n log n); up to 10⁶: O(n).
- n up to 10⁹ or more: O(log n) or a formula.
Revise: Common growth rates and estimating from constraints (opens in a new tab)
Next step
Check your understanding
12 quick questions