Draw a triangle of a given height, as in the example. Tip: Make use of the…
- User
Draw a triangle of a given height, as in the example.
Tip: Make use of the str.center(length) method that centers a string and fills the missing space on both sides with spaces.
Sample Input 1:
3
Sample Output 1:
Hint by avatar Franck Alain Binde Koube For those with a solution probably working "fine" in IDE but not here, check the leading space of your output. Was this hint helpful? Write a program in Python 3
- Assistant
To draw a centered triangle of a given height, we can calculate the maximum width of the triangle and center each line accordingly. The maximum width is determined by the formula
2 * height - 1, which corresponds to the number of characters in the base of the triangle.Here's the Python 3 code that accomplishes this:
n = int(input()) max_width = 2 * n - 1 for i in range(1, n + 1): num_hashes = 2 * i - 1 line = '#' * num_hashes print(line.center(max_width))This code works as follows:
- It reads the input
n, which is the height of the triangle. - It calculates
max_width, which is the width of the base of the triangle. - It iterates from
1ton(inclusive) to build each line of the triangle. - For each line, it calculates the number of
#characters (num_hashes) needed. - It creates the line by repeating
#num_hashestimes. - It centers the line within the
max_widthusing thecenter()method and prints it.
This will output the triangle with the correct leading spaces and ensure that it matches the expected output format.
- It reads the input