0

what is wrong with my code to generate the folowing output. I need to use recursive function to complete the program but I get the wrong output.

def computeTriangle(levels):
`
    if levels == 0:
        return []
    elif levels == 1:
        return [[1]]
    elif levels == 2:
        return [[1], [1, 1]]
    else:
        triangle = computeTriangle(levels - 1)
        prev_row = triangle[-1]
        row = [1]
        for i in range(1, levels - 1):
            row.append(prev_row[i - 1] + prev_row[i])
        row.append(1)
        triangle.append(row)
        return triangle


def printTriangle(triangle, levels):
    if levels == 0:
        return`your text`
    printTriangle(triangle, levels - 1)
    for j in range(levels):
        print(triangle[levels - 1][j], end=' ')
    print()


def main():
    levels = 5
    triangle = computeTriangle(levels)
    printTriangle(triangle, levels)


if __name__ == '__main__':
    main()

I expect to get this output: 1

1 1

2 1 2

3 2 2 3

5 3 4 3 5

but I get this output: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1

Maria
  • 1

1 Answers1

0

i guess this is pascal triangle, you can try this :

def pascals_array(numRow):
        if numRows == 1:
            return [[1]]
        result = pascals_array(numRows-1)
        return result + [[1] + [result[-1][i-1] + result[-1][i] for i in range(1,numRows-1)] + [1]] 

or you can use this :

# input n
n = 5
 
for i in range(1, n+1):
    for j in range(0, n-i+1):
        print(' ', end='')
 
    # first element is always 1
    C = 1
    for j in range(1, i+1):
 
        # first value in a line is always 1
        print(' ', C, sep='', end='')
 
        # using Binomial Coefficient
        C = C * (i - j) // j
    print()
Hamza
  • 7
  • 3