Skip to content

Instantly share code, notes, and snippets.

@andychase
Last active August 29, 2015 14:24
Show Gist options
  • Save andychase/ed86743be6ca26d4d244 to your computer and use it in GitHub Desktop.
Save andychase/ed86743be6ca26d4d244 to your computer and use it in GitHub Desktop.
Split a number into tuples in a unique way each time
""" Andy Chase
>>> [number_to_unique_tuple(i, 256) for i in [0, 1, 2, 255, 256]]
[(0,), (1,), (2,), (255,), (0, 1)]
>>> [number_to_unique_tuple(i, 256, 1) for i in [0, 1, 2, 255, 256]]
[(0, 0), (1, 1), (2, 2), (255, 255), (0, 1)]
>>> [number_to_unique_tuple(i, 256) for i in [256*2, (256*256) - 2, (256*256) - 1, 256*256]]
[(0, 2), (254, 253), (255, 254), (0, 0, 1)]
>>> s = [number_to_unique_tuple(i, 256) for i in range(0,256*256)]
>>> len(list(s))
65536
>>> len(set(s)) == len(list(s))
True
"""
import math
def number_to_unique_tuple(n, split_at, min_splits=0):
return tuple(_number_to_unique_tuple(n, split_at, min_splits))
def _number_to_unique_tuple(n, split_at, min_splits):
if n == 0:
number_of_splits = 0
else:
number_of_splits = math.floor(math.log(n, split_at))
number_of_splits = max(number_of_splits, min_splits)
yield n % split_at
for i in range(0, number_of_splits):
yield (n + (n // split_at ** (i + 1))) % split_at
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment