Reputation: 81
I've been given a homework assignment that asks to print an equilateral triangle with '*' as the frame and inside the triangle a string of fixed number of '$' and spaces is supposed to run.
example: Enter height: 9 Enter number of $: 5 Enter number of spaces: 2
I am lost here, help?
Upvotes: 0
Views: 370
Reputation: 2162
Let's see over what logic it works. You will find code at last.
*
*
*
*
First thing is how many spaces on the left of each star is equal to TOTAL_HEIGHT_OF_PATTERN - CURRENT_HEIGHT_STATUS
. for given example let's take 2nd-line
so:
TOTAL_HEIGHT_OF_PATTERN = 4
CURRENT_HEIGHT_STATUS = 2
NUMBER_OF_SPACE_ON_LEFT = TOTAL_HEIGHT_OF_PATTERN - CURRENT_HEIGHT_STATUS = 2
*
*$*
*$$$*
* $$$*
*$$$$$ *
*$$$$$ $$*
*$$$$$ $ $*
*$$$ $$$$$$*
How many spaces at given height, for above system it is found.
spaces:0 for height @ 1, 2, 3
spaces:1 for height @ 4, 5, 6
spaces:2 for height @ 7, 8
Instead of completely using loop let's divide them in procedural code. For making particular enclose-string
we can use make_str function
who logic revolves around the remaining number of $
CODE :
height = int(input('Height : '))
doller = int(input('Dollor : '))
spaces = int(input('Spaces : '))
def make_str(rem, len_str):
x = 0
s = ''
for _ in range(len_str):
if rem >0:
s += '$'
rem -= 1
else:
s += ' '
x += 1
if x == spaces:
x = 0
rem = 5
return (rem, s)
rem_dollor = doller
for i in range(1,height+1):
num = 2*(i)-3
rem_dollor, str_ = make_str(rem_dollor, num)
if i == 1:
print(' '*(height-i) + '*')
elif i != height and i != 1:
print(' '*(height-i) + '*' + str_ + '*')
else:
print('*'*(2*height-1))
OUTPUT :
Height : 9
Dollor : 5
Spaces : 2
*
*$*
*$$$*
*$ $$*
*$$$ $$*
*$$$ $$$$*
*$ $$$$$ $*
*$$$$ $$$$$ *
*****************
Upvotes: 3