Code bij Telling op een helling

De tabel

[[ 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100],
 [ 1, 2, 5, 10, 17, 26, 37, 50, 65, 82, 101],
 [ 4, 5, 8, 13, 20, 29, 40, 53, 68, 85, 104],
 [ 9, 10, 13, 18, 25, 34, 45, 58, 73, 90, 109],
 [ 16, 17, 20, 25, 32, 41, 52, 65, 80, 97, 116],
 [ 25, 26, 29, 34, 41, 50, 61, 74, 89, 106, 125],
 [ 36, 37, 40, 45, 52, 61, 72, 85, 100, 117, 136],
 [ 49, 50, 53, 58, 65, 74, 85, 98, 113, 130, 149],
 [ 64, 65, 68, 73, 80, 89, 100, 113, 128, 145, 164],
 [ 81, 82, 85, 90, 97, 106, 117, 130, 145, 162, 181],
 [ 100, 101, 104, 109, 116, 125, 136, 149, 164, 181, 200]]

tel_Mu

def tel_Mu(tabel, x):
    totaal = 0
    for rij in tabel:
        for waarde in rij:
            if waarde == x:
                totaal = totaal + 1
    return totaal

tel_Milli

def tel_Milli(tabel, x):
    return sum(w == x
               for rij in tabel
               for w in rij)

tel_Phi

def tel_Phi(f, M, N, x):
    return sum(f(i, j) == x
               for i in range(M)
               for j in range(N))

tel_Pi

def tel_Pi(f, M, N, x):
    totaal, i, j = 0, M - 1, 0
    while i >= 0 and j < N:
        w = f(i, j)
        if w < x:
            j = j + 1
        elif w > x:
            i = i - 1
        else: # w == x
            totaal = totaal + 1
            i, j = i - 1, j + 1
    return totaal

Aanroep tel_pi

tel_Pi(lambda i, j: i*i + j*j,
       1_000_001, 1_000_001,
       1_000_000_000_000)

Tweede tabel

[[1, 1, 1, 2, 2, 2, 2, 2, 3],
 [1, 2, 2, 2, 3, 3, 3, 4, 4],
 [1, 2, 3, 3, 3, 4, 4, 4, 5],
 [2, 2, 3, 4, 4, 4, 5, 5, 6],
 [2, 3, 3, 4, 5, 5, 5, 6, 6],
 [2, 3, 4, 4, 5, 6, 6, 6, 7],
 [2, 3, 4, 5, 5, 6, 7, 7, 7],
 [2, 4, 4, 5, 6, 6, 7, 8, 8],
 [3, 4, 5, 6, 6, 7, 7, 8, 9]]

definitief: tel

def tel(f, M, N, x):
    totaal, i, j = 0, M - 1, 0
    while i >= 0 and j < N:
        if f(i, j) <= x:
            totaal = totaal + i + 1
            j = j + 1
        else : # x < f(i, j)
            i = i – 1
    return totaal