Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursively print pyramid of numbers

I have to print a pyramid of numbers with this rule:

odd index: 1 to index, even index: index to 1:

1
21
123
4321
12345
654321
1234567
87654321
123456789

I wrote this code:

def printFigure(rows):
    if rows > 0:
        if rows%2 == 0:
            printFigure(rows-1)
            while(rows>0):
                print(str(rows)[::-1], end = '')
                rows -= 1
            print('')

        if rows%2 == 1:
            printFigure(rows-1)
            while (rows>0):
                print(str(rows),end = '')
                rows -= 1
            print('')

but the output is:

1
21
321,
4321
54321
654321
7654321
87654321
987654321

I'm a beginner with recursion, I'll be glad for your explanations too. thanks.

like image 800
Benny Avatar asked Nov 29 '18 10:11

Benny


1 Answers

You have two major problems with your current code. First, the check on whether the rows is even or odd should be happening after the recursive call to printFigure. The reason for this is that it is after backing out from the recursive call that you want to decide to print the line in order or backwards.

The second problem was with the logic in the else printing condition. You need to print starting at 1, up to the number of rows. I used a dummy variable to achieve this, though there are probably a few other ways of doing it.

def printFigure(rows):
    if rows > 0:
        printFigure(rows-1)
        if rows%2 == 0:
            while(rows>0):
                print(str(rows)[::-1], end='')
                rows -= 1
            print('')
        else:
            i = 1
            while (i <= rows):
                print(str(i), end='')
                i += 1
            print('')

printFigure(9)

1
21
123
4321
12345
654321
1234567
87654321
123456789
like image 167
Tim Biegeleisen Avatar answered Nov 14 '22 07:11

Tim Biegeleisen