Home > Back-end >  How to sort the numbers without repeating in the next line in Python
How to sort the numbers without repeating in the next line in Python

Time:11-01

This is my code and this is wrong

i = ''
for a in range (1,37):
    i  = str(a) ' '
    print(i)

This is the output i want

This is the output i want

CodePudding user response:

Try this way:

def contnum(n):
    num = 1
    for i in range(0, n):
        for j in range(0, i 1):
            print(num, end=" ")
            num = num   1
            print("\r")
         
n = 5       
contnum(n)

CodePudding user response:

An option is to use itertools.count:

import itertools

n = 8
c = itertools.count(start=1)

for i in range(1, n   1):
    print(' '.join(str(next(c)) for _ in range(i)))

(Actually you don't need join; you can just use unpacking: print(*(next(c) for _ in range(i))))

If you don't want to import a module, but you are willing to use walrus operator (python 3.8 ),

n = 8
c = 0
for i in range(1, n   1):
    print(*(c := c   1 for _ in range(i)))

Output:

1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35 36

CodePudding user response:

limit,a, k = 37,1, 1
while a < limit:
    print(' '.join(str(x) for x in range(a, min(a   k,limit))))
    a  = k
    k  = 1

Output:

1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35 36

CodePudding user response:

One way using itertools.islice and count, and iter's sentinel:

it = iter(range(1, 37))
n = count(1)
f = lambda : list(islice(it, next(n)))
list(iter(f, []))

Output:

[[1],
 [2, 3],
 [4, 5, 6],
 [7, 8, 9, 10],
 [11, 12, 13, 14, 15],
 [16, 17, 18, 19, 20, 21],
 [22, 23, 24, 25, 26, 27, 28],
 [29, 30, 31, 32, 33, 34, 35, 36]]

Or if you want to print:

for i in iter(f, []):
    print(*i)

Output:

1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35 36

CodePudding user response:

You can also do it like this:-

n=1
for i in range(8):
    for j in range (i 1):
        print(n,end=' ')
        n  = 1
    print()

CodePudding user response:

My entry for code golf:

for n in range(1, 9):
    print(*range(1 n*(n-1)//2, 1 n*(n 1)//2))

produces the expected outcome.

  • Related