Whether you are going to start your GCSE Computer Science course next term or are already halfway through, it’s always a good time to do some coding practice.
Here’s a fun intermediate level challenge for all you coding enthusiasts out there.
Coding Pascal’s Triangle with Python
Pascal’s Triangle is a fascinating mathematical structure which contains many patterns. Each element in a row is formed by adding the two elements above it in the preceding row. There are many uses for the triangle in areas such as probability and counting the ways things can be combined (e.g. how many pizza types are possible with 5 available toppings?). Make sure you understand how the triangle is constructed, and then
Write a program which displays every row of Pascal’s Triangle for a given value of
nis the number of rows.
The approach used in my solution below is to build each new row from the previous row using
nested for loops resulting in a
list of lists. Before looking at my solution, be sure to have a really good go at it yourself. Another approach would be to think about how each term in a given row is generated, and build each row using the appropriate formula. To keep things simpler, the output should be left-aligned. E.g:
1 1 1 1 2 1 1 3 3 1 1 4 6 4 1
Good luck, and I hope you enjoy the challenge. If you want to, let me know how you got on in the comments below.
# Pascal's Triangle def pascal(n): """Returns a 2D list containing rows of Pascal's Triangle up to the nth.""" triangle = [] for i in range(n - 1): new_row =  for j in range(i): new_row.append( triangle[i][j] + triangle[i][j + 1] ) new_row.append(1) triangle.append(new_row) return triangle result = pascal(4) # One way to print out a 2D list for row in result: for item in row: print(item, end=" ") print()