K
K
KatSmi2021-12-21 14:10:15
Python
KatSmi, 2021-12-21 14:10:15

How to display line by line integers from 1 to N, not more than C numbers per line?

I wrote the code, but I'm worried that it can be made simpler and more convenient - improved.
"""
N - The number of numbers to be split into lines
C - The number of numbers in the line
"""

def line_break(N, C):
    s = [i for i in range(1, (N+1))]
    y = 0

    while y <= len(s):
        print(*s[0:C], end="\n")
        y += 1
        del s[0:C]

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
DudkevichD, 2021-12-21
@DudkevichD

I do not know how much easier and more convenient it is. You also need to take into account that s may not be a multiple of C and then there will be an exception, so you can use try to avoid this.

def line_break(N, C):
    s = [i for i in range(1, (N+1))]

    while s:
        try:
            print(s[:C])
            del s[:C]
        except:
            print(s)

D
Drill, 2021-12-21
@Drill

def line_break(limit, step):
    for i in range(1, (limit+1)):
        yield str(i) + ' '
        if i % step == 0:
            yield '\n'

print(''.join(line_break(14, 4)))
1 2 3 4 
5 6 7 8 
9 10 11 12 
13 14

print(''.join(line_break(25, 5)))
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

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question