Skip to content

Instantly share code, notes, and snippets.

@zevaverbach
Created November 8, 2021 11:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zevaverbach/aad209a1224967c298fe55695e302e88 to your computer and use it in GitHub Desktop.
Save zevaverbach/aad209a1224967c298fe55695e302e88 to your computer and use it in GitHub Desktop.
Partition a list in Python 3.7
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