This post explores some different ways of generating the famous Triangle Numbers with Python.
Before reading on, have a go a writing some Python code to print out the first 10 Triangle Numbers.
TRIANGLE NUMBERS USING A LIST
The first approach we will look at involves building up a list of Triangle Numbers by using a loop and the append
list method.
n = 10
triangle_nums = []
tri_num = 0
for i in range(1, n + 1):
tri_num += i
triangle_nums.append(tri_num)
print(triangle_nums)
"""
Output: [1, 3, 6, 10, 15, 21, 28, 36, 45, 55]
"""
TRIANGLE NUMBERS USING THE FORMULA
There is a simple formula for calculating the n
th Triangle Number, and it comes with a lovely and easy-to-understand proof, which you can learn about here.
The code is shown below. It uses a for
loop and end=","
inside the call to print()
, to keep output on the same line, separated by commas.
for n in range(1, 11):
print((n * (n + 1)) // 2, end=",")
"""
Output: 1,3,6,10,15,21,28,36,45,55,
"""
PARITY PATTERN IN TRIANGLE NUMBERS
Did you know that there is a pattern in the parity (oddness/evenness) of the triangle numbers?
You can see this from these results where T(n)
is the n
th Triangle Number, and P(T(n))
is its remainder on division by 2.
n T(n) P(T(n))
1 1 1
2 3 1
3 6 0
4 10 0
5 15 1
6 21 1
7 28 0
8 36 0
9 45 1
10 55 1
11 66 0
12 78 0
13 91 1
14 105 1
The code for producing the above results is:
print("n\tT(n)\tP(T(n))") # \t is an escape character for tab
for n in range(1, 15):
t = (n * (n + 1)) // 2
p = t % 2
print(n, "\t", t, "\t", p)
If you are into Maths, you may like to think about how this pattern arises. There are different ways to reason about it, but one involves the fact that all positive integers leave a remainder of either 0, 1, 2
or 3
on division by 4
.
TRIANGLE NUMBERS USING A GENERATOR
Another approach, which is a great example for starting to learn about the Python keyword yield
is shown below.
The
yield
keyword in Python used to exit from a function without disturbing the state of local variables, and when the function is called again, execution starts from the point where the code was left.
# Triangle numbers using a generator
def triangular_numbers(n):
i, ti = 2, 1 # i is the counter, ti is the ith triangle number
while i <= n + 1:
yield ti
ti += i
i += 1
print(list(triangular_numbers(10)))
"""
Output: [1, 3, 6, 10, 15, 21, 28, 36, 45, 55]
"""
This post has shown some ways that we can use Python to generate Triangle Numbers. Each approach has its advantages and disadvantages, but they all produce the correct result. You may want to practice by trying them out for yourself now that you have seen them, and have a go at implementing one or more of them without looking back at this post.
Happy computing!
Nice post. This has given me some ideas for introducing this to A level computer science students as a possible unseen programming task. I like the linking between Python and theoretical Maths. This will definitely please the Math students in my class!