patternpythonMinor
Creating a page number array for pagination
Viewed 0 times
paginationnumbercreatingarrayforpage
Problem
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:
The function is:
Is there anything to do to improve this code, or is there any other simpler methods to achieve this?
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)1:
a.insert(0,a[0]-1)
if a[-1]<max:
a.append(a[-1]+1)
return aIs there anything to do to improve this code, or is there any other simpler methods to achieve this?
Solution
- Review
-
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.
-
The number 5 is arbitrary, so I would make it a parameter to the function.
-
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.
- 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)Code Snippets
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)Context
StackExchange Code Review Q#92137, answer score: 9
Revisions (0)
No revisions yet.