0

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

enter image description here

I am lost here, help?

1
  • Please post your code. Commented Apr 23, 2021 at 21:42

1 Answer 1

3

Let's see over what logic it works. You will find code at last.

1st.

How to create left-side star pattern like this :
    *
   *
  *
 *

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

2nd.

How to create `$` and `space` pattern like this in between: (BOTTOM PATTERN IS ONLY FOR VISUALIZATION)
        *
       *$*
      *$$$*
     *  $$$*
    *$$$$$  *
   *$$$$$  $$*
  *$$$$$  $  $*
 *$$$    $$$$$$*

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
        *
       *$*
      *$$$*
     *$  $$*
    *$$$  $$*
   *$$$  $$$$*
  *$  $$$$$  $*
 *$$$$  $$$$$  *
*****************
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.