Python 3D Academyবাংলা

How to solve a problem: a method that always works

🌍 In real life. Planning a family trip to Cox's Bazar, you don't book a hotel first. You find out what everyone wants (how many days, what budget), you remember how last year's trip went, you make a simple plan that works, then you look for ways to make it cheaper or faster, and finally you check it: are the dates right, is everyone included?

Solving a programming problem goes the same way. Welcome to data structures and algorithms: from now on we don't just make programs work, we make them work well, and we can say why they are correct and how fast they are.

The idea in one sentence: an algorithm is a step-by-step recipe that turns an input into the right output, and a good one does it without wasted work.

Its words:

  • input and output: what the program is given, and what it must give back
  • constraints: the limits the problem promises, like "the list is never empty" or "n is at most 1,000"
  • edge case: an unusual input at the border of what is allowed: an empty list, one item, every item the same
  • brute force: the plain solution that tries everything; slow, but a safe first answer to check faster ones against

The five steps, every time:

  1. Understand. What goes in (the input)? What must come out (the output)? Any limits (the constraints), like "the list is never empty"?
  2. Examples. Work two or three small cases by hand, including the awkward ones (edge cases): an empty list, one item, everything the same.
  3. Brute force. Write the simplest solution that is surely correct, even if it is slow. It is your safety net.
  4. Improve. Find the wasted work in the brute force, and remove it.
  5. Test. Run your examples, especially the edge cases.

Worked example: the pair problem. Given a list of prices and a budget, do two different items add up to exactly the budget? For [30, 70, 45, 25] and a budget of 100: yes, 30 + 70.

Brute force: try every pair. For each item, compare it with every item after it. It is surely correct, because no pair is skipped. With n items it checks n(n-1)/2 pairs: 6 pairs for 4 items, 4950 for 100 items. That number grows like n², and later lessons call this O(n²).

Improve: the wasted work is looking back over the same items again and again. Instead, remember every price seen so far in a set (Chapter 10). For each price p, the partner it needs is budget - p: if that is already in the set, we found a pair. Each item is looked at once, so the work grows like n.

def has_pair_slow(prices, budget):
    checks = 0
    for i in range(len(prices)):
        for j in range(i + 1, len(prices)):
            checks += 1
            if prices[i] + prices[j] == budget:
                return True, checks
    return False, checks

def has_pair_fast(prices, budget):
    seen = set()
    checks = 0
    for p in prices:
        checks += 1
        if budget - p in seen:
            return True, checks
        seen.add(p)
    return False, checks

prices = [45, 25, 60, 15, 30, 70]
print(has_pair_slow(prices, 100))
print(has_pair_fast(prices, 100))
print(has_pair_slow(prices, 1000))
print(has_pair_fast(prices, 1000))
Here the pair (30 + 70) is the last two prices, so the slow way checks all 15 pairs of 6 prices before finding it; the fast way looks at each price once (6 checks). With no pair at all it is the same: 15 against 6. The gap gets huge as the list grows.

Mistakes and edge cases. Can an item pair with itself? Here it can't: with [50] and a budget of 100 the answer is No, and the fast version gets it right because it checks the set before adding p. Also try the empty list (no pairs at all) and duplicates ([50, 50] should be Yes).

Quiz

  1. What should you do first when you meet a new problem?

    • Understand the input, the output and the limits
    • Write the fastest code you can think of
    • Start testing random inputs
  2. How many pairs does the nested loop check? What does this print?

    items = ["a", "b", "c", "d"]
    checks = 0
    for i in range(len(items)):
        for j in range(i + 1, len(items)):
            checks += 1
    print(checks)
  3. Why write a brute-force solution first, even if it is slow?

    • It is surely correct, so you can check faster versions against it
    • Brute force is always fast enough
    • Interviewers only want brute force
  4. What does this print?

    seen = set()
    found = False
    for p in [40, 25, 60]:
        if 100 - p in seen:
            found = True
        seen.add(p)
    print(found, len(seen))
  5. With [50] and a budget of 100 this says True, but one item can't pair with itself. Which line is wrong?

    def has_pair(prices, budget):
        seen = set()
        for p in prices:
            seen.add(p)
            if budget - p in seen:
                return True
        return False

Coding tasks

  1. Write the brute force has_pair(prices, budget): True if two different items add up to exactly budget, otherwise False. Try every pair.

  2. Now the improved way: write has_pair_fast(prices, budget) that looks at each price once, remembering the prices seen so far in a set.

  3. Make the cost visible: write pair_checks(n) that runs the brute force's two loops over n items and gives back how many pairs they check.