-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution.py
61 lines (46 loc) · 2.38 KB
/
solution.py
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# PaginationHelper
# For this exercise you will be strengthening your page-fu mastery.
# You will complete the PaginationHelper class,
# which is a utility class helpful for querying paging information related to an array.
# The class is designed to take in an array of values
# and an integer indicating how many items will be allowed per each page.
# The types of values contained within the collection/array are not relevant.
# The following are some examples of how this class is used:
# helper = PaginationHelper(['a','b','c','d','e','f'], 4)
# helper.page_count # should == 2
# helper.item_count # should == 6
# helper.page_item_count(0) # should == 4
# helper.page_item_count(1) # last page - should == 2
# helper.page_item_count(2) # should == -1 since the page is invalid
# page_ndex takes an item index and returns the page that it belongs on
# helper.page_index(5) # should == 1 (zero based index)
# helper.page_index(2) # should == 0
# helper.page_index(20) # should == -1
# helper.page_index(-10) # should == -1 because negative indexes are invalid
import math
class PaginationHelper:
# The constructor takes in an array of items and a integer indicating
# how many items fit within a single page
def __init__(self, collection, items_per_page):
self._collection = collection
self._items_per_page = items_per_page
# returns the number of items within the entire collection
def item_count(self):
return len(self._collection)
# returns the number of pages
def page_count(self):
return int(math.ceil(1.0 * self.item_count() / self._items_per_page))
# returns the number of items on the current page. page_index is zero based
# this method should return -1 for page_index values that are out of range
def page_item_count(self, page_index):
if (page_index + 1) * self._items_per_page <= self.item_count():
return self._items_per_page
if page_index * self._items_per_page < self.item_count() < (page_index + 1) * self._items_per_page:
return self.item_count() % self._items_per_page
return -1
# determines what page an item is on. Zero based indexes.
# this method should return -1 for item_index values that are out of range
def page_index(self, item_index):
if self.item_count() > item_index >= 0:
return int(item_index / self._items_per_page)
return -1