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?

200_success
145k22 gold badges190 silver badges478 bronze badges
asked May 29, 2015 at 10:44
\$\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)
answered May 29, 2015 at 14:18
\$\endgroup\$
1
  • \$\begingroup\$ Just remembered I shouldn't use max as a variable name. \$\endgroup\$ Commented May 30, 2015 at 9:52

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.