What Is an Algorithm: From Everyday Steps to Pseudocode
Welcome to the Advanced Python and Algorithms course. In the previous course you used variables, loops, lists, and functions. Now our focus shifts: not just writing programs that run, but programs that are correct and fast. The key is the algorithm.
Definition
An algorithm is a clear, finite sequence of steps for solving a problem. A good algorithm has five properties:
- Input: the data being processed, for example a list of test scores.
- Output: the requested result, for example the highest score.
- Definite: every step has exactly one meaning.
- Finite: it always stops after a limited number of steps.
- Correct: it gives the right output for every valid input.
Example: a homeroom teacher finds the highest score
Mrs. Rina is holding 36 maths test sheets and wants to know the highest score. She does not look at all the sheets at once. She takes the first sheet and remembers its score, then opens the next sheets one by one. Each time she finds a larger score, she replaces the score she remembers. After the last sheet, the remembered score is the answer.
We can write those steps as pseudocode, half-human writing that is not bound by the rules of any particular programming language:
ALGORITMA NilaiTertinggi(daftar)
tertinggi ← elemen pertama daftar
UNTUK setiap nilai DI daftar:
JIKA nilai > tertinggi MAKA
tertinggi ← nilai
KEMBALIKAN tertinggi
Its translation into Python is almost line by line:
def nilai_tertinggi(daftar):
tertinggi = daftar[0]
for nilai in daftar:
if nilai > tertinggi:
tertinggi = nilai
return tertinggi
print(nilai_tertinggi([78, 92, 85, 92, 60])) # 92
Tracing step by step
For the input [78, 92, 85, 92, 60]: at first tertinggi = 78. The value 78 is not larger, 92 is larger so tertinggi becomes 92, then 85, 92, and 60 are not larger. The result is 92. Following the steps like this is called tracing, and we will do it often.
Notice the requirement too: this algorithm assumes the list is not empty. A requirement like this is called a precondition. Throughout the course we will always ask two questions about every algorithm: is it correct for all inputs, and how fast is it when there is a lot of data.