I have these two functions:
def comparison(a, b):
return [-1, 0, 1].index(cmp(b, a))
def base_3(seq):
return [comparison(a, b) for a, b in itertools.combinations(seq, 2)]
The function comparison returns a comparison number based on this:
- 0 if a > b
- 1 if a = b
- 2 if a < b
The function base_3 returns the comparison among all combined elements.
For instance:
x = [0, 1, 2]
y = [1, 2, 0]
z = [0, 1, 0]
>>> base_3(x)
[2, 2, 2]
>>> base_3(y)
[2, 0, 0]
>>> base_3(z)
[2, 1, 0]
I need a function that return a sequence from a given base_3, when possible:
>>> base_3_to_seq([2, 2, 2])
[0, 1, 2]
>>> base_3_to_seq([2, 1, 0])
[0, 1, 0]
>>> base_3_to_seq([0, 2, 1])
"Impossible"
How can I write this function base_3_to_seq?
This is a brute force way:
Depending upon which way you’re calling it most, you could speed the code up for long runs by memoizing either base_3 or base_3_to_seq.