I1 · Python Programming for AI

From Problem to Algorithm

An algorithm is a finite sequence of precise, unambiguous steps that takes some input and produces the required output. A good algorithm is correct (it always gives the right answer), complete (it covers every case) and finishes in a finite number of steps.

8 min Intermediate Jump to the activity

What you need: The earlier topics of this module.

Definition

Could a robot make tea from your instructions, exactly as written?

An algorithm is a finite sequence of precise, unambiguous steps that takes some input and produces the required output. A good algorithm is correct (it always gives the right answer), complete (it covers every case) and finishes in a finite number of steps.

In simple words

"Make tea" is not an algorithm, because a robot doesn't know what to do. "Fill the pan with one cup of water, heat until it boils, add one spoon of tea leaves…" is closer. Every programmer first works out the steps, then writes them in a programming language. The language changes; the thinking doesn't.

Why it matters

Most programming bugs come from unclear thinking, not from typing. Writing the algorithm first, in plain words, shows the gaps before any code exists. Every AI method in this course, from search to neural networks, is an algorithm.

How it works

Input, steps, output

PartLargest of three numbers
InputThree numbers a, b and c
StepsAssume a is largest. If b is bigger, b becomes largest. If c is bigger than that, c becomes largest.
OutputThe largest number

How to check an algorithm

  • Is every step precise enough that a machine could follow it without guessing?
  • Does it handle every case, including ties and empty inputs?
  • Does it always stop?

Try it yourself

Write the steps to find the largest of three numbers

Put the steps in an order that always works.

  1. 1Read the three numbers a, b and c
  2. 2If c is greater than largest, set largest to c
  3. 3Output largest
  4. 4Set largest to a
  5. 5If b is greater than largest, set largest to b

Precise or vague?

Could a machine follow each instruction without guessing?

  • Repeat 10 times: add 1 to count

  • If the mark is 40 or more, output PASS, otherwise output FAIL

  • Add a little salt

  • Sort the list nicely

Common mistakes

  • Starting to type code before knowing the steps.
  • Forgetting edge cases, such as two equal numbers or an empty list.
  • Writing steps that only a person could follow, such as 'pick a good one'.

Check yourself

Question 1

1. Which is an algorithm?

Question 2

2. For largest of a = 4, b = 9, c = 2, what is largest after step 3 above?

Question 3

3. Why write the algorithm before the code?

Summary

  • An algorithm is precise, complete steps from input to output that always finish.
  • Write it in plain words first; translate it into a language later.
  • Check it for precision, every case, and stopping.

Finished reading?

Sources: W3Schools DSA with Python