Python小型分页器:基于总数据量生成分页起止区间的最优方案
max_number into 5 Index Ranges Alright, let's cut to the chase—splitting your dataset into 5 balanced index ranges is straightforward with basic arithmetic, and this method is as fast as it gets (O(1) time since we're only dealing with 5 fixed ranges).
Here's the core logic:
- Calculate the base size of each range by dividing
max_numberby 5 using integer division. - Handle the remainder (leftover items that don't fit evenly into 5 chunks) by adding 1 extra item to the first N ranges, where N equals the remainder.
Example with max_number = 423
423 ÷ 5 = 84 (base size), remainder 3. So the first 3 ranges get 85 items each, the last 2 get 84 items—perfectly balanced.
Code Implementation (Python)
This works for both 0-based (programming) and 1-based (SQL) indices—just uncomment the line that matches your use case:
def get_query_ranges(max_number, num_ranges=5): base_size = max_number // num_ranges remainder = max_number % num_ranges ranges = [] current_start = 0 for i in range(num_ranges): # Calculate size of current range (add extra if we haven't used up the remainder) range_size = base_size + (1 if i < remainder else 0) current_end = current_start + range_size # For 0-based indices (e.g., Python lists) ranges.append((current_start, current_end - 1)) # end is exclusive, so subtract 1 # For 1-based indices (e.g., SQL queries) # ranges.append((current_start + 1, current_end)) # Move start to the end of this range for the next iteration current_start = current_end return ranges
Testing with 423
Running get_query_ranges(423) returns:
[(0, 84), (85, 169), (170, 254), (255, 338), (339, 422)]
Each of the first 3 ranges has 85 items, the last 2 have 84—exactly what you need for balanced subset queries.
Edge Cases
- If
max_number < 5: The firstmax_numberranges will have 1 item each, the rest will return empty ranges (e.g.,max_number=3gives[(0,0), (1,1), (2,2), (3,2), (3,2)]). You can add a check to skip empty ranges if needed, but the function still generates the 5 ranges as requested. - If
max_number = 0: Returns 5 empty ranges—adjust this behavior if your use case requires handling empty datasets differently.
This method is optimal because it uses only basic arithmetic operations—no loops over the entire dataset, no expensive memory allocations, just a fixed number of calculations. It doesn't get faster than this.
内容的提问来源于stack exchange,提问作者Omar Gonzales

