Algorithms

Input, process, output — a recipe the computer can follow.

An algorithm is a finite recipe: input, process, output. It must terminate, and every step must be unambiguous.

Goal

Write a total algorithm and a max algorithm, and print both results.

Input, process, output

units = [12, 7, 2, 9]

def total(xs):
    acc = 0
    for x in xs:
        acc += x
    return acc

print(total(units))
print(total([]))

Empty input is allowed: the total of nothing is 0.

Maximum

def maximum(xs):
    if not xs:
        raise ValueError("maximum of empty list")
    best = xs[0]
    for x in xs[1:]:
        if x > best:
            best = x
    return best

print(maximum([10.5, 22.0, 31.0, 22.0]))
print(maximum([7]))

Each comparison is a step. The recipe does not say “use max()” — it says how to find it.

Finite

def countdown(n):
    while n > 0:
        print(n)
        n -= 1
    print("open")

countdown(3)

n -= 1 guarantees the loop ends. An algorithm that never reaches the output is not useful.

Pitfall

while True with no break is not an algorithm you can finish. This course wants recipes that stop.