'Can't figure out how to format this python loop answer properly (get rid of trailing spce)
I don't understand what they want from me. After tinkering over an hour, I finally have an answer that appears to look right but my homework's portal is telling me it doesn't like the spacing. There is an extra space at the very end of each line that I need to get rid of and I don't know how.
This program will output a right triangle based on user specified height triangle_height and symbol triangle_char.
(1) The given program outputs a fixed-height triangle using a * character. Modify the given program to output a right triangle that instead uses the user-specified triangle_char character. (1 pt)
(2) Modify the program to use a loop to output a right triangle of height triangle_height. The first line will have one user-specified character, such as % or *. Each subsequent line will have one additional user-specified character until the number in the triangle's base reaches triangle_height. Output a space after each user-specified character, including a line's last user-specified character. (2 pts)
Example output for triangle_char = % and triangle_height = 5:
Enter a character:
%
Enter triangle height:
5
%
% %
% % %
% % % %
% % % % %
My code:
triangle_char = input('Enter a character:\n')
triangle_height = int(input('Enter triangle height:\n'))
print('')
for i in range(triangle_height):
print(" ".join("{}".format((i+1)*triangle_char)))
1: Compare output 0 / 1
Output is nearly correct; but whitespace differs. See highlights below.
Input @ 3
Your output
Enter a character:
Enter triangle height:
@
@ @
@ @ @
Expected output
Enter a character:
Enter triangle height:
@
@ @
@ @ @
2: Compare output 0/1
Output is nearly correct; but whitespace differs. See highlights below.
Input
%
5
Your output
Enter a character:
Enter triangle height:
%
% %
% % %
% % % %
% % % % %
Expected output
Enter a character:
Enter triangle height:
%
% %
% % %
% % % %
% % % % %
3: Compare output 0 / 1
Output is nearly correct; but whitespace differs. See highlights below.
Input
m
4
Your output
Enter a character:
Enter triangle height:
m
m m
m m m
m m m m
Expected output
Enter a character:
Enter triangle height:
m
m m
m m m
m m m m
Solution 1:[1]
Avoid printing extra spaces after the last column and don't print newline after the last row.
Lets test it out hope below logic will help you.
def pattern(ch, height):
for row in range(1, height+1):
for col in range(1, row+1):
print(ch, end= ' ' if col != row else '')
if row != height:
print()
ch = str(input()) #character
height = int(input()) #height of the triangle
pattern(ch=ch, height=height)
Output:
%
5
%
% %
% % %
% % % %
% % % % %
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
