Omar Gonzales
Omar Gonzales

Reputation: 4008

Python - Small paginator

Let's say I have a max_number defined by sistem.

For example: 423

I need, in this case, 5 list:

I'll use the 2 items in the list has my from - to indicators to make a subset of a db table.

from - to:

[1,100]
[101,200]
[201,300]
[301,400]
[401,423]

What would be the quickest approach of doing this?

I have this function but it's still buggy:

def paginator(desde,cantidad_maxima):
    lst = []
    if(cantidad_maxima < 100):
        lst.append(desde)
        lst.append(cantidad_maxima)
        print(lst)
    hasta = 100

    lst.append(desde)
    lst.append(hasta)

    print('Primera vuelta del paginador:')
    print(lst)

    while hasta < cantidad_maxima:
        desde = desde + 100
        hasta = hasta + 100 + (cantidad_maxima%100)

        lst.append(desde)
        lst.append(hasta)

        print('Desde - Hasta:')
        print(lst)

paginator(1, 423) # returns [1, 100, 101, 223, 201, 346, 301, 469]

Upvotes: 1

Views: 90

Answers (2)

Thomas K&#252;hn
Thomas K&#252;hn

Reputation: 9810

You can use a simple list comprehension to achieve what you want.

EDIT: After the OP updated the question, the requirements have changed a bit. Here now the updated solution:

upper = 423
stride = 100

intervals = [[i,i+stride-1 if i+stride-1 < upper else upper] for i in range(1,upper+1,stride)]

print(intervals)

this gives:

[[1, 100], [101, 200], [201, 300], [301, 400], [401, 423]]

Upvotes: 2

Jongware
Jongware

Reputation: 22447

As a one-line list comprehension:

max = 423
intervals = [[x*100+1,x*100+100] for x in range(0,max//100)]+([[100*(max//100)+1,max]] if max%100 else [])
intervals
>>> [[1, 100], [101, 200], [201, 300], [301, 400], [401, 423]]

This is built up from the following components:

  1. range(0,max//100) yields a list [0, 1, 2, 3]
  2. Each of these items gets added as [x * 100, x * 100+100] to result in [[0, 100], [100, 200], [200, 300], [300, 400]]
  3. The first value in each pair needs incrementing by 1. The +1 takes care of that.
  4. This leads to a list of whole hundreds only, so the remainder must be added: .. +([[100*(max//100)+1, max]], which is a short list [401, 423].
  5. (icing on the cake) ... except when max is a round hundreds number, of course. In that case, if expects an else and so I add an empty list [], which does not contribute anything to the result.

    a. ... and it needs a further if in case this last segment is the only one.

Some more results (list comprehension left out for clarity):

max = 96
>>> [[1, 96]]

max = 100
>>> [[1, 100]]

max = 101
>>> [[1, 100], [101, 101]]

Upvotes: 1

Related Questions