2

I have a potentially long array of one's and zero's that looks like this: a = [0,0,1,0,1,0,.....] I want to translate each consecutive pair of values to an integer between 0 & 3 as shown below:

  • 0,0 -> 0
  • 0,1 -> 1
  • 1,0 -> 3
  • 1,1 -> 2

I'm looking for a nice clean efficient way to create the array b (example output below) using the mapping above: b = [0, 3, 3,...]

Is a dict a good idea? I can't figure out how to do it though.

3 Answers 3

4

Try:

x = np.reshape(a, (-1,2))

b = x[:,0]*2 + (x[:,0] ^ x[:,1])
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for figuring out the way to use a function. I was thinking I'd have to create a map.
1

If you want to use a dict with an explicit mapping between corresponding decimal numbers, you could try this:

# Convert to a (-1,2) matrix and decimal numbers first
a = np.reshape(a, (-1,2))
a = np.sum(np.array([2,1])*a, axis=1)

# Define dictionary with mapping
D = {0: 0, 1: 1, 2: 3, 3: 2}

# Apply dictionary
a = [D[x] for x in a]

1 Comment

Thanks. I had the reshape idea but kept trying to figure out how to use a 2 element array as the key in a dict.
1

You could use the successive pairs as indices to perform a look-up, for getting the translated value:

master = np.array([[0, 1],[3, 2]])
b = master[a[::2], a[1::2]]

Test input:

[1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1]

Output:

[2, 1, 2, 2, 1, 1, 0, 3]

2 Comments

The mapping given in the question would be standard for Gray code. There's no reason to assume it's a typo.
@user2357112supportsMonica -- Thanks for pointing out. I've now modified my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.