Code that looks right
Read · 1 of 4
Fast, confident, and sometimes wrong
AI tools write code in seconds, and it usually looks clean and sure of itself. Most of the time it's right. Sometimes it's wrong in a way that only shows up on one kind of input.
In this course you're the detective: read code you didn't write, find the input that breaks it, fix it, and judge whether it's fast enough. Every program here is a real one: what you're told about it was checked by running it.
Read this lesson as text
Three short programs that look fine. Are they?
Fast, confident, and sometimes wrong
AI tools write code in seconds, and it usually looks clean and sure of itself. Most of the time it's right. Sometimes it's wrong in a way that only shows up on one kind of input.
In this course you're the detective: read code you didn't write, find the input that breaks it, fix it, and judge whether it's fast enough. Every program here is a real one: what you're told about it was checked by running it.
The average
n = int(input()) nums = list(map(int, input().split())) print(sum(nums) // n)
This should print the average of the numbers (it can be a decimal, like 2.5). Is it right?
- Yes, it's correct
- No: it drops the decimals, so
1 2gives1instead of1.5 - No: it crashes when the numbers are negative
Show the answer
No: it drops the decimals, so 1 2 gives 1 instead of 1.5. // divides and throws the decimals away. / keeps them. One character, and the answer is wrong for most inputs.
The biggest number
n = int(input())
nums = list(map(int, input().split()))
best = 0
for x in nums:
if x > best:
best = x
print(best)This should print the biggest number. When does it go wrong?
- Never: it's correct
- When every number is negative
- When the list has repeats
Show the answer
When every number is negative. best starts at 0, so with -5 -2 -9 nothing beats it and it prints 0, a number that isn't even in the list. Start from the first number instead.
Counting evens
n = int(input())
nums = list(map(int, input().split()))
count = 0
for x in nums:
if x % 2 == 0:
count += 1
print(count)This should count the even numbers (negatives and zero included). Is there a bug?
- It's correct
- Wrong for negatives:
-3 % 2is negative in Python - Wrong for zero
Show the answer
It's correct. In Python -3 % 2 is 1 and -4 % 2 is 0, so negatives work, and zero is even. Part of reviewing is saying "this is fine" with confidence, not finding a bug in everything.