Created
November 8, 2021 11:45
-
-
Save zevaverbach/aad209a1224967c298fe55695e302e88 to your computer and use it in GitHub Desktop.
Partition a list in Python 3.7
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import Dict, Tuple, Any, List | |
def make_tuple_partitions( | |
unique_values: List[Any], num_partitions: int | |
) -> Dict[Tuple[int, int], Tuple[Any, Any]]: | |
""" | |
Given a list of values, return a dictionary with (the_index, the_index + 1) as the keys | |
and (chunk_start_value, chunk_end_value) as the values such that the chunks are equal | |
or close to equal in size. | |
The last key's 1th value should be -1. | |
""" | |
length = len(unique_values) | |
if length < num_partitions: | |
raise NotEnoughValues | |
if length == num_partitions: | |
return unique_values | |
first, last = unique_values[0], unique_values[-1] | |
chunk_size = int(length / num_partitions) | |
prev_end = chunk_size | |
prev_value = first | |
index_of_last_chunk = length - chunk_size - 1 | |
partitions = [] | |
for index in range(chunk_size, index_of_last_chunk, chunk_size): | |
partitions.append((prev_value, unique_values[index])) | |
prev_end = index | |
prev_value = unique_values[index] | |
partitions.append((prev_value, last)) | |
partition_dict = {} | |
last_idx = len(partitions) - 1 | |
for idx, value in enumerate(partitions): | |
if idx == last_idx: | |
key = (idx, -1) | |
else: | |
key = (idx, idx + 1) | |
partition_dict[key] = value | |
return partition_dict |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment