← all tracks/Puzzle Workshop: Explorer

Searching: Find It Fast

Searching: Find It Fast πŸ”

Welcome to the Puzzle Workshop! From now on, problems won't tell you exactly what to type β€” they'll tell you what they want, and you design the plan. First skill: searching.

The moment a program has a bunch of things instead of one thing, the very first question is always the same: is the thing I want in here, and where? You already know lists and loops β€” searching is what they were training for.

The searching loop

Almost every search is this shape:

found = False
for item in items:
    if item == target:
        found = True

From that one shape come dozens of variations: stop at the first match or scan to the last, return a position or a count or a yes/no, hunt for the biggest or the closest or the first one that breaks a rule.

Best-so-far

The other superstar pattern of this unit:

best = nums[0]
for n in nums:
    if n > best:
        best = n

Change one comparison and it finds the smallest, the longest, the closest to zero β€” anything.

About shortcuts

Python has in, .index(), max(), min() β€” and you'll earn them. In this unit, write the loops yourself. When you can build a search with your bare hands, the shortcuts stop being magic and start being yours.

And waiting at the top of this topic is the smartest search of all: binary search, where a sorted list lets you throw away half the possibilities with every guess. Let's go!

# problems