Processing math: 100%

Triangular numbers

This function defines a generator for the triangular numbers, Tn=nk=1k=1+2+3++n, for n=0,1,2,: that is, Tn=0,1,3,6,10,.

def triangular_numbers(n):
    i, t = 1, 0
    while i <= n:
        yield t
        t += i
        i += 1

>>> list(triangular_numbers(15))
[0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105]

Note that the statements after the yield statement are executed each time triangular_numbers resumes. The call to triangular_numbers(15) returns an iterator which feeds these numbers into list to generate a list of its values.