find match index group in python

Rizki Arif Source

What the simplest wayto determine which index group is searched in python


desire value

Yes, Yes, No

value provided

A = No, No, No
B = Yes, No, No
C = Yes, Yes, No

We want to know which index group matches A, B, or C?



answered 1 week ago abarnert #1

I'm going to take a wild leap into the dark here and guess what you're trying to do. If I've guessed wrong, this answer will be useless, and I'll delete it.

Your example is that if input is [Yes, No, Yes], it should match C, which is Yes, Yes, No. So presumably you want to know if input has the same elements—in any order—as any of A, B, and C.

One way to do this is by using collections.Counter as a multiset:

from collections import Counter

A = Counter(('No', 'No', 'No'))
B = Counter(('Yes', 'No', 'No'))
C = Counter(('Yes', 'Yes', 'No'))

input = ['Yes', 'No', 'Yes']
input_multiset = Counter(input)

if input == A:
elif input == B:
elif input == C:
    print('no match')

Now, there are ways you could simplify and/or optimize this, but the best way is to rethink the problem. The difference between A, B, and C is just how many Yes values each has. So:

from collections import Counter

abc = {0: 'A', 1: 'B', 2: 'C']

input = ['Yes', 'No', 'Yes']
input_counts = Counter(input)
yes_count = input_counts['Yes']
print(abc.get(yes_count, 'no match'))

comments powered by Disqus