Python Sequence elements comparison

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:

  1. 0 if a > b
  2. 1 if a = b
  3. 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])

How can I write this function base_3_to_seq?


This is a brute force way:

def base_3_to_seq(base3):
   for seq in itertools.product(range(3), repeat=3):
       if base_3(seq) == base3:
           return seq
   return "Impossible"

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.

Need Your Help

How can you update location data in Windows Phone in the background?

windows-phone-7 location background-process background-agents

I just read that while Windows Phone 7.5 background tasks can poll for a location, they don't actually poll real-time from the GPS but rather the location API calls return a system-cached position ...

Generate repeating hexagonal pattern with CSS3

html css css3 css-shapes

So, I need to make a repeating hexagonal pattern, using CSS. If images are needed, I can go there, but I'd prefer to just use CSS if possible.