It's a really simple question but I don't understand where I'm wrong. Let's say there's an array of numbers A = [a, b, c, d, ...]
, and each element is in range [0, N)
. I want to convert this array to a single number (and back), almost like if these elements are digits of a number in base N
. So for example, for N == 64
:
seq_to_num([0, 0, 0, 0]) == 0
seq_to_num([0, 0, 0, 1]) == 1
seq_to_num([0, 0, 1, 0]) == 64
seq_to_num([63, 63, 63, 63]) == 64**4 - 1
num_to_seq(67, 4) == [0, 0, 1, 3]
Bruteforce solution is to have smth like
import itertools
def seq_to_num(seq):
for i, c in enumerate(itertools.product(range(BASE), repeat = 4)):
if c == seq:
return i
But it's quite an overkill to use iteration here in my opinion. And for reversing the number I would need to keep an array of combinations and things get pretty ugly.
I know it's super trivial, but I'm getting wrong numbers. Here's my code:
BASE = 64
def seq_to_num(seq):
size = len(seq)
return sum([pow(BASE, size - i) * digit for i, digit in enumerate(seq)])
def num_to_seq(num, places):
seq = [0] * places
while num != 0:
num, rem = divmod(num, BASE)
seq.insert(0, rem)
return reversed(seq)
What am I missing?