E4.13Triangular numbers
This function defines a generator for the triangular numbers, \(T_n = \sum_{k=1}^{n}k = 1 + 2 + 3 + \cdots + n\), for \(n=0,1,2,\cdots\): that is, \(T_n = 0, 1, 3, 6, 10, \cdots\).
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.