Building an Algorithm: Search and Count

Part of: Programming Lab: Python for CSP

An Algorithm Is a Plan. An algorithm is a clear sequence of steps that solves a problem. Two of the most common are searching (does a value appear?) and counting (how many match a rule?). Both walk through a list once and keep track of what they find. Linear Search. A linear search checks each item in turn until it finds the target or runs out. You can track success with a Boolean flag . The flag found starts False. If any item equals the target, it flips to True. After the loop, the flag tells you the answer. This visit-each-item pattern is the backbone of countless algorithms. Counting Matches. Counting uses the same walk but with an accumulator instead of a flag. Here you count how many numbers are above a threshold. Start the count at 0, add 1 each time the rule holds, and print the total. The shape is always the same: set up a result, loop and update it, then report it. What usually goes wrong. What you see What caused it How to fix it --- --- --- The answer is always no, even when the word is clearly there The flag was reset back to False inside the loop, wiping out an earlier match Set the flag once before the loop, and only ever flip it inside The answer is always yes The f

Challenge: Search the List