Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print numbers serially in columns

I am struggling in one of the Pattern matching problems in Python

When input = 3, below is the expected output (input value is the number of columns it should print)

Expected output:

1
2 6
3 7 9
4 8
5

I am somehow moving in a wrong direction, hence would need some help in it.

This is the code I have tried so far:

def display(): 
        n = 5
        i = 1
        # Outer loop for how many lines we want to print 
        while(i<=n):  
            k = i 
            j = 1
  
            # Inner loop for printing natural number 
            while(j <= i):  
                print (k,end=" ") 
                  
                # Logic to print natural value column-wise 
                k = k + n - j 
                j = j + 1
                  
            print("\r") 
            i = i + 1
  
#Driver code 
display() 

But it is giving me output as this:

1 
2 6 
3 7 10 
4 8 11 13 
5 9 12 14 15 

Anybody who can help me with this?

like image 425
pik Avatar asked Dec 18 '22 11:12

pik


1 Answers

n=10
for i in range(1,2*n):
    k=i
    for j in range(2*n-i if i>n else i):
        print(k,end=' ')
        k = k + 2*n - 2*j - 2
    print()

Result

1 
2 20 
3 21 37 
4 22 38 52 
5 23 39 53 65 
6 24 40 54 66 76 
7 25 41 55 67 77 85 
8 26 42 56 68 78 86 92 
9 27 43 57 69 79 87 93 97 
10 28 44 58 70 80 88 94 98 100 
11 29 45 59 71 81 89 95 99 
12 30 46 60 72 82 90 96 
13 31 47 61 73 83 91 
14 32 48 62 74 84 
15 33 49 63 75 
16 34 50 64 
17 35 51 
18 36 
19 
> 
like image 122
jeypee Avatar answered Dec 29 '22 18:12

jeypee