Minjae Lee
Minjae Lee

Reputation: 41

Python: How to make numeric triangle with recursion

while I was working on the Python practice, I found a question that I cannot solve by myself. The question is,

Input one integer(n), and then write the codes that make a triangle using 1 to 'n'. Use the following picture. You should make only one function, and call that function various times to solve the question. The following picture is the result that you should make in the codes. Receive one integer as an argument, print the number from 1 to the integer received as a factor in a single line, and then print the line break character at the end. Once this function is called, only one line of output should be printed. this is the following picture

So by that question, I found that this is a question that requires the recursion since I have to call your function only once. I tried to work on the codes that I made many times, but I couldn't solve it.

global a
a = 1

def printLine(n):
 global a
 if (n == 0):
     return

 for i in range(1, a + 1):
 print(i, end=" ")
 print()
  a += 1

 for k in range(1, n+1):
     print(k, end=" ")
 print()

 printLine(n - 1)

 n = int(input())
 printLine(n)

Then I wrote some codes to solve this question, but the ascending and descending part is kept overlapping. :( What I need to do is to break two ascending and descending parts separately in one function, but I really cannot find how can I do that. So which part should I have to put the recursive function call? Or is there another way can divide the ascending and descending part in the function? Any ideas, comments, or solutions are appreciated. Thx

Upvotes: 1

Views: 533

Answers (3)

Arthur Lacerda
Arthur Lacerda

Reputation: 68

Using default parameter as a dict, you can manipulate it as your function variables, so in that way, you can have a variable in your function that keeps the current iteration you are at and if your function is ascending or descending.

def triangle_line(n, config={'max':1, 'ascending':True}):
    print(*range(1, config['max'] + 1))

    if config['ascending']:
        config['max'] += 1
    else:
        config['max'] -= 1

    if config['max'] > n:
        config['ascending'] = False
        config['max'] = n
    elif config['max'] == 0:
        config['ascending'] = True
        config['max'] = 1

Each call you make will return one iteration.

>>> triangle_line(4)
1
>>> triangle_line(4)
1 2
>>> triangle_line(4)
1 2 3
>>> triangle_line(4)
1 2 3 4
>>> triangle_line(4)
1 2 3 4
>>> triangle_line(4)
1 2 3
>>> triangle_line(4)
1 2
>>> triangle_line(4)
1

Or you can run on a loop, two times your input size.

>>> n = 4
>>> for i in range(0,n*2):
...     triangle_line(n)
... 
1
1 2
1 2 3
1 2 3 4
1 2 3 4
1 2 3
1 2
1

Upvotes: 0

Eyal Ben-Ivri
Eyal Ben-Ivri

Reputation: 31

# function  to print all the numbers from 1 to n with spaces
def printLine(k):
  # create a range. if k is 4, will create the range: 1, 2, 3, 4
  rng = range(1, k + 1)
  # convert each number to string
  str_rng = map(lambda x: str(x), rng)
  # create one long string with spaces
  full_line = " ".join(str_rng)
  print(full_line)

# capture input
n = int(input())

# start from 1, and up to n, printing the first half of the triangle
for i in range(1, n):
  printLine(i)

# now create the bottom part, by creating a descending range
for i in range(n, 0, -1):
  printLine(i)

Upvotes: 0

dildeolupbiten
dildeolupbiten

Reputation: 1342

You can use the below function:

def create_triangle(n, k: int = 1, output: list = []):
    if n == 1:
        output.append(n)
        return output
    elif k >= n:
        output.append(" ".join([str(i) for i in range(1, n + 1)]))
        return create_triangle(n - 1, k)
    else:
        output.append(" ".join([str(i) for i in range(1, n + 1)[:k]]))
        return create_triangle(n, k + 1)


for i in create_triangle(5):
    print(i)

Output:

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1

Upvotes: 1

Related Questions