MJames28
MJames28

Reputation: 37

How do I grab the last X lines of a right triangle created using recursion?

So I am trying to create two functions (the use of additional functions is allowed). One that creates an entire right triangle by calling a recursive function, and then the recursive function itself is suppose to be able to grab the last X amount of lines of the complete right triangle and display them. The only thing is, the first function (triangle()) cannot be changed.

Here are the two functions (at least this is what I have so far for the recursive function):

def triangle(n):
    return recursive_triangle(n, n)


def recursive_triangle(k, n):
    if k > 0:
        print(k*'*')
        recursive_triangle(k-1, n)

So for example, when working properly:

triangle(6)

would give

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

and

recursive_triangle(3,6)

would give me the last 3 lines of a right triangle of base and height 6 (above triangle) like so:

***
 **
  *

I'm not sure how to use the relationship between n and k in a recursive method to implement the proper spacing required.

Upvotes: 0

Views: 70

Answers (2)

bashBedlam
bashBedlam

Reputation: 1500

I think this is what you want.

print( (n-k) * ' ' + k * "*")

Upvotes: 1

zwer
zwer

Reputation: 25809

If I understand you correctly, triangle(6) should show a 6-lines tall triangle. This, I presume, also means that triangle(3) should show a 3-lines tall triangle, just as you presented in your example so there is no need to change anything (in the setup), you just need to write the recursive_triangle() function properly to subtract k from n before sending it to another function to do the actual printing.

However, what I think you want is to still consider the 'whole' triangle, but just not print the higher lines, i.e. instead of:

***
 **
  *

you want:

   ***
    **
     *

Notice the extra indentation as if the 'triangle' was printed but was missing the first 3 lines. In that case, you can use str.rjust() to do the justification for you, e.g.:

def recursive_triangle(k, n):
    if k > 0:
        print(("*" * k).rjust(n))
        recursive_triangle(k-1, n)

Now if you call recursive_triangle(3, 6) you'll get exactly what you're after (and it will also properly print deferred calls from triangle()).

UPDATE: If you want to return a string instead of printing, store the results in a list and then concatenate with new lines, i.e.:

def recursive_triangle_builder(k, n):
    result = []
    if k > 0:
        result.append(("*" * k).rjust(n))
        result += recursive_triangle_builder(k-1, n)
    return result

def recursive_triangle(k, n):
    return "\n".join(recursive_triangle_builder(k, n))

print(recursive_triangle(3, 6))  # or store the result instead of printing

Upvotes: 1

Related Questions