Spelling It Out: Progressive Substring List
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.
Deep Dive
1. The Challenge: Progressive Prefix Slicing
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"].
2. Why It Matters
Building progressive prefixes is used in auto-complete search bars, prefix tree (trie) data structures, and type-ahead suggestions.
3. The Python Solution
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']
4. How Slice txt[:i] Works
- When
i = 1:txt[:1]extracts index 0 ("e"). - When
i = 2:txt[:2]extracts indices 0 to 1 ("ea"). - When
i = 4:txt[:4]extracts full word ("eats").
5. Common Mistakes
- Off-By-One Range Limit: Writing
range(1, len(txt))misses the final full word! Always uselen(txt) + 1to include the complete string slice.
6. Next Steps
Use txt[:i] for cumulative prefixes. Next, let's extract city facts from Python dictionaries!
Next Up in Python Beginner Practice & Core Problem Solving
Return the Sum of Two Numbers
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.
Convert Minutes into Seconds
`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.
Calculate the Area of a Triangle
`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.