Python Exercise: Print out the first n rows of Pascal's triangle
Python Functions: Exercise-13 with Solution
Write a Python function that prints out the first n rows of Pascal's triangle.
Note : Pascal's triangle is an arithmetic and geometric figure first imagined by Blaise Pascal.
Sample Pascal's triangle :
Each number is the two numbers above it added together
Sample Solution :
Python Code :
# Define a function named 'pascal_triangle' that generates Pascal's Triangle up to row 'n'
def pascal_triangle(n):
# Initialize the first row of Pascal's Triangle with value 1 as a starting point
trow = [1]
# Create a list 'y' filled with zeros to be used for calculations
y = [0]
# Iterate through a range starting from 0 up to the maximum of 'n' or 0 (taking the maximum to handle negative 'n')
for x in range(max(n, 0)):
# Print the current row of Pascal's Triangle
print(trow)
# Update the current row based on the previous row by calculating the next row using list comprehension
# The formula for generating the next row in Pascal's Triangle is based on addition of consecutive elements
trow = [l + r for l, r in zip(trow + y, y + trow)]
# Return True if 'n' is greater than or equal to 1, else return False
return n >= 1
# Generate Pascal's Triangle up to row 6 by calling the 'pascal_triangle' function
pascal_triangle(6)
Sample Output:
[1] [1, 1] [1, 2, 1] [1, 3, 3, 1] [1, 4, 6, 4, 1] [1, 5, 10, 10, 5, 1]
Explanation:
In the exercise above the code defines a function named "pascal_triangle()" that generates Pascal's Triangle up to a specified row 'n'. It uses a list 'trow' to represent each row and y as an auxiliary list for calculations. The function iterates through the rows of the triangle, printing each row and updating it based on the previous row's values using list comprehension. Finally, it generates Pascal's Triangle up to row 6 by calling the "pascal_triangle()" function.
Flowchart:
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python function that checks whether a passed string is palindrome or not.
Next: Write a Python function to check whether a string is a pangram or not.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-exercises/python-functions-exercise-13.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics