abd
abd

Reputation: 155

How to create right angle number triangle using python

code is below

def right_angle(lines):
    result = []
    result = [[0 for i in range(lines)] for i in range(lines)]
    for i in range(lines):
        for j in range(lines-i-1):
            print(" ",end=" ")
        for j in range(i+1):
            print(j+ 1, end=' ')
        print( )
    #return result
right_angle(4)

My out

      1 
    1 2 
  1 2 3 
1 2 3 4

Expected is

[[0 0 0 1] 
[0 0 1 2] 
[0 1 2 3] 
[1 2 3 4]]

Upvotes: 0

Views: 484

Answers (2)

James E
James E

Reputation: 301

You could probably condense this a bit, but it works. You literally just forgot to add the [] and did ' ' instead of '0 '.

def right_angle(lines):
    result = []
    result = [[0 for i in range(lines)] for i in range(lines)]
    for i in range(lines):
        if i == 0:
            print('[[',end='')
        else:
            print('[',end='')
        for j in range(lines-i-1):
            print("0",end=" ")
        for j in range(i+1):
            print(j+ 1, end=' ')
        print(']', end='')
        if i == lines-1:
            print(']')
        print( )
    #return result
right_angle(4)

Upvotes: 1

Barmar
Barmar

Reputation: 780724

Instead of printing spaces and numbers, append 0 and numbers in your loops.

And you should append lines-i 0's, not lines-i-1.

def right_angle(lines):
    result = []
    for i in range(lines):
        row = []
        for j in range(lines-i):
            row.append(0)
        for j in range(1, i+1):
            row.apend(j)
        result.append(row)
    retrn result

This can be simplified to:

def right_angle(lines):
    result = []
    for i in range(lines):
        result.append([0] * (lines-i) + list(range(1, i+1)))
    return result

Upvotes: 1

Related Questions