Course Problem Solving & Algorithms With Python

The Problem-Solving Process

Thinking Like a Programmer Preview

How to attack any problem

Great programmers do not think faster — they follow a reliable process. Use this loop every time you are stuck.

The four steps

  1. Understand — restate the problem in your own words; list inputs and expected outputs
  2. Plan — sketch the approach, start with a brute-force idea
  3. Implement — write the smallest working version
  4. Reflect — test edge cases, simplify, improve speed

Worked example: find the largest number

def largest(nums):\n    if not nums:\n        return None\n    best = nums[0]\n    for n in nums[1:]:\n        if n > best:\n            best = n\n    return best

Test cases come first

assert largest([3, 9, 2, 7]) == 9\nassert largest([-5]) == -5\nassert largest([]) is None\nprint("all tests pass")

Edge cases checklist

  • Empty input
  • Single element
  • All same values
  • Negative numbers
  • Very large values

When stuck

  • Solve a tiny example by hand
  • Draw a diagram
  • Write out the brute-force version first
  • Explain the problem out loud
Tip: Write the tests before the function. It forces you to understand the problem — the hardest 20% of any task.

This is a free preview lesson

Enroll in the Problem Solving & Algorithms With Python to unlock every lesson, lesson PDF guides, quizzes and your certificate - and start creating your own pieces today.


Discussion

Free preview lesson