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. Key takeaways: - An algorithm is an ordered sequence of steps for a problem. - Linear search checks each item until it finds the target. - A flag records whether something happened; an accumulator counts how often. - Set up, loop and update, then report the result.
Challenge: Search the List