Quick Overview
`s[:i]` copies the first `i` characters, so building every prefix of a string totals `O(n^2)` work. Fine for a word, worth knowing before it meets a large input.
Create a function spelling(txt) that takes a word and spells it out by progressively building a list of substring prefixes. For example, "eats" should return ["e", "ea", "eat", "eats"].
Building progressive prefixes is used in auto-complete search bars, prefix tree (trie) data structures, and type-ahead suggestions.
Use a list comprehension slicing txt[:i] over range indices:
def spelling(txt):
return [txt[:i] for i in range(1, len(txt) + 1)]
# Testing our function
print(spelling("eats")) # Output: ['e', 'ea', 'eat', 'eats']
print(spelling("bee")) # Output: ['b', 'be', 'bee']
print(spelling("happy")) # Output: ['h', 'ha', 'hap', 'happ', 'happy']
i = 1: txt[:1] extracts index 0 ("e").i = 2: txt[:2] extracts indices 0 to 1 ("ea").i = 4: txt[:4] extracts full word ("eats").range(1, len(txt)) misses the final full word! Always use len(txt) + 1 to include the complete string slice.Use txt[:i] for cumulative prefixes. Next, let's extract city facts from Python dictionaries!
A function with no `return` hands back `None`, so a forgotten one surfaces as a `TypeError` at the call site rather than at the line that actually caused it.
`minutes * 60` returns an `int` when given an `int`, while `/` always produces a float regardless of the operands. Multiplication preserves the type; division does not.
`base * height / 2` always yields a float in Python 3 because `/` never returns an int, even for whole numbers. `//` floors instead, which is almost never what an area wants.