Amazon Online Assessment (OA) - Fetch Items To Display

Solution

Explanation

We sort the results by the sortColumn and order. Then using the pageSize and the pageIndex, we can figure out the number of results on the previous pages and the index of the first result of the target pageIndex page. For example, pageIndex = 1 and pageSize = 2, there are 1 * 2 = 2 results on page 0 so the index the first result of page 1 should be 2. Finally we return all the results on the target page.

1
1
from typing import Dict, List, Tuple
2
2
3
3
def fetch_results_to_display(sort_column: int, sort_order: int, results_per_page: int, page_index: int, results: Dict[str, Tuple[int, int]]) -> List[str]:
4
-
    # WRITE YOUR BRILLIANT CODE HERE
4
+
    ordered = [(name, rel, price) for name, (rel, price) in results.items()]
5
-
    return []
5
+
    ordered.sort(key=lambda x: x[sort_column], reverse=sort_order == 1) # sort by sort_column and reverse order if needed
6
+
    start_index = results_per_page * page_index # find the start index of the first result on the target page
7
+
    return [name for name, _, _ in ordered[start_index:start_index + results_per_page]] # return only the name of each result on the page
8
+
6
9
if __name__ == '__main__':
7
10
    sort_column = int(input())
8
11
    sort_order = int(input())
9
12
    results_per_page = int(input())
10
13
    page_index = int(input())
Expand 8 lines ...