Most mistakes in algorithm problems are not about the algorithms themselves but about language details and boundaries. They repeat again and again, so it is worth knowing them by sight. Below are seven typical Python traps and a way to find the bug once it has happened.
* shares one inner list; a comprehension creates separate ones1. Off-by-one
An error by one occurs in loop bounds, slices and binary search. Remember: range(a, b) and the slice s[a:b] do not include b, and indices start at zero, so the last index is len(a) - 1.
n = 5
total = 0
for i in range(1, n): # stops at 4: n is missing
total += i
print(total)10n = 5
total = 0
for i in range(1, n + 1): # the end of range() is exclusive
total += i
print(total)15Check the boundaries on a tiny input: n = 0, n = 1, n = 2.
2. Mutable default value
A default value is created once, when the function is defined, and from then on it is the same list:
def add_item(x, items=[]):
items.append(x)
return items
print(add_item(1))
print(add_item(2))
print(add_item(3, []))
print(add_item.__defaults__)[1]
[1, 2]
[3]
([1, 2],)