Fix the request count for a pagination loop
Your task
Your client pages through a REST API with a loop that stops when a page comes back with fewer than per_page items. The loop passed a smoke test against 250 items. Before it ships, you want to compare its cost with a loop that reads the API's own total.
An assistant wrote page_request_counts(total_items, per_page) to count the requests each loop makes. It is in the editor. It has a bug. Find it and fix it.
Input and output:
total_items: how many items the collection holds.per_page: how many items a full page holds.- Return
[contract_calls, short_page_calls], or[]when the input is invalid.
Rules the tests check:
- The input is invalid when
per_pageis 0 or less, ortotal_itemsis less than 0. contract_callsis the number of pages needed to holdtotal_items, rounded up, and at least 1: you always make the first call, even for an empty collection.short_page_callsis how many calls the short page loop makes. It requests pages 1, 2, 3 and so on, and stops right after the first page that holds fewer thanper_pageitems. An empty page counts as one of those.
Examples
page_request_counts(total_items: int, per_page: int) -> list[int]Example 1
Input
page_request_counts(250, 100)Output
[3, 3]Example 2
Input
page_request_counts(300, 100)Output
[3, 4]Example 3
Input
page_request_counts(0, 100)Output
[1, 1]