Home > Software design >  How can I resolve this whitespace issue in my recurssion question
How can I resolve this whitespace issue in my recurssion question

Time:05-03

LAB: Drawing a right side up triangle

Write a recursive function called draw_triangle() that outputs lines of * to form a right side up isosceles triangle. Function draw_triangle() has one parameter, an integer representing the base length of the triangle. Assume the base length is always odd and less than 20. Output 9 spaces before the first * on the first line for correct formatting.

Hint: The number of * increases by 2 for every line drawn.

Ex: If the input of the program is:

3

the function draw_triangle() outputs:

        *
       ***

Ex: If the input of the program is:

19

the function draw_triangle() outputs:

         *
        ***
       *****
      *******
     *********
    ***********
   *************
  ***************
 *****************
*******************

Note: No space is output before the first * on the last line when the base length is 19.

I have been able to figure out the recursion part but I cant figure out getting the right white space to the left of the triangle

CodePudding user response:

If I understand your problem correctly, you see that the "top" of the triangle, always has one * in it. Then if the base of the triangle is n, the "top" row should have n - 1 spaces in it.

Continuing the pattern you can see that with every row under the top, you add 2 *'s. Then any given row will have n - 2r - 1 spaces if r is the row (starting from the top, r = 0).

Here's the cool part, since you know n is odd (given in question) and 2r is definitely even, then n - 2r - 1 is always going to be even. Call half this number the "whitespace amount" and print out that amount of spaces for each row (and remember, the row r starts from 0).

Here's some pseudo code

def print_triangle(width, row):
   if 2 * row   1 == width: # if you are in the last row
       for i < 2 * row   1:
           print("*") # print the *
       return # break out of recursion
   else:
       for i < (width - 2 * row - 1) / 2:
           print(" ") # print whitespace
       for i < 2 * row   1:
           print("*") # print the *
   return print_triangle(width, row   1) # recursive call

of course there are many more ways to do this, some of which will have more concise code, but hopefully this pseudo code helps you understand the logic behind the program.

CodePudding user response:

You can't just have a single variable for recursion:
This code would help you:

def draw_triangle(n,i):
    if(n<=0):
        return 
    print(" "*(n//2),end="")
    print("*"*i)
    draw_triangle(n-2,i 2)
draw_triangle(19,1)

Output:

         *
        ***
       *****
      *******
     *********
    ***********
   *************
  ***************
 *****************
*******************

Hope this helps you. Here i=1 since you need to print 1 star at the begining.

  • Related