12
\$\begingroup\$

I have written a small function to generate an array of page numbers for displaying a pagination. The inputs to the function is an active page number p, and the max page number. The function will return an array of 5 possible page numbers available near the active page.

Example input, output:

pages(1,10): [1,2,3,4,5]

pages(10,10): [6,7,8,9,10]

pages(5,10): [3,4,5,6,7]

The function is:

def pages(p,max):
    a=[p]
    while len(a)<5 and not (a[0]==1 and a[-1]==max):
        if a[0]>1:
            a.insert(0,a[0]-1)
        if a[-1]<max:
            a.append(a[-1]+1)
    return a

Is there anything to do to improve this code, or is there any other simpler methods to achieve this?

\$\endgroup\$
0

1 Answer 1

9
\$\begingroup\$

1. Review

  1. The function needs a docstring to explain what it does, with maybe some examples. The explanation in your post is very good: this is exactly the kind of thing that should go into the docstring.

  2. The number 5 is arbitrary, so I would make it a parameter to the function.

  3. The implementation takes time proportional to the number of entries in the page range. It would be more elegant to compute the endpoints of the range directly, taking constant time.

2. Revised code

def page_range(page, last, span=5):
    """Return a range of page numbers around page, containing span pages
    (if possible). Page numbers run from 1 to last.

    >>> list(page_range(2, 10))
    [1, 2, 3, 4, 5]
    >>> list(page_range(4, 10))
    [2, 3, 4, 5, 6]
    >>> list(page_range(9, 10))
    [6, 7, 8, 9, 10]

    """
    return range(max(min(page - (span - 1) // 2, last - span + 1), 1),
                 min(max(page + span // 2, span), last) + 1)
\$\endgroup\$
1
  • \$\begingroup\$ Just remembered I shouldn't use max as a variable name. \$\endgroup\$
    – rahul
    May 30, 2015 at 9:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.