Christos Antonak - 9 months ago 40

Python Question

I have two lists a & b, with equal length N and values between [0, 1]. I want to check each pair of the two lists with same index (a[0] with b[0], a[1] with b[1] and so on) and based on their values, measure how many times the belong as pair to one of the following states.

Each element of the list can be in one of the following state:

1) [0]

2) (0, 0.1]

3) (0.1, 0.2]

.....

11)(0.9, 1)

12) [1]

My issue is that each element of a or b can be in one of those 12 states so their pairs have the possibility of being in one of the 12 * 12 = 144 final states.

Pair State <- State a & State b

Final State 1 <-State 1 & State 1

Final State 2 <-State 1 & State 2

Final State 3 <-State 1 & State 3

....

Final State 144 <- State 12 & State 12

If I only had one list the problem could be solved with a simple for loop and if/else statements. I zipped the two lists, but then the combinations are too many to proceed.

Any ideas?

As an example if I have:

a = [0, 0.1, 0.25, 0.1]

b = [1, 0.1, 0.4, 0.05]

There 144 defined possible pair of states so from the above 4 we have

State 1 & State 12 = 1 (from a[0]-b[0])

State 2 & State 2 = 2 (from a[1]-b[1] and a[3]-b[3])

State 4 & State 5 = 1 (from a[2]-b[2])

Answer

If I get this right, given your two lists, you need to find out how many "pairs" contain items from the same interval.

Here's a little trick you could use:
Multiply by ten, then use `int()`

to get rid of the decimal part.

```
a = [.11, .22, .33, .55]
b = [.16, .28, .38, .60]
pairs = 0
for (x, y) in zip(a, b):
if int(x*10) == int(y*10):
pairs += 1
print(pairs)
```

If zero is a state in itself, then you will need to adapt what I've posted above to account for that, since `int(0*10)`

and `int(0,09*10)`

gives the exact same result.

Following edits to the question : if you do have a "matrix" of states, then there might actually be a simple way out of this.

```
w = 12
states = [[0 for x in range(w)] for y in range(w)] # Beware of [[0]*12]*12, that doesn't work
for (x, y) in zip(a, b):
if (x != 0):
sx +=1
if (y != 0):
sy += 1
states[sx][sy] += 1
```

This creates a 12*12 table, and for each pair, increments the "cell" it belongs to. From there, you need to extract the number of pairs and prefix them with the appropriate "state x + state y" labels.

Last notes : if you are to output the result to a console, you might want to use the `pprint`

module.