Checking if some values in a set meet a specific condition in Python

Viewed 161

In a Python program, I have a list of lists of tuples:

x = [[(frozenset({(5, 'Y')}), 5, 'Y')],
     [(frozenset({(9, 'Y'), (2, 'Y'), (7, 'N'), (3, 'Y')}), 2, 'Y'),
      (frozenset({(4, 'Y'), (0, 'Y'), (8, 'N'), (1, 'Y')}), 4, 'Y'),
      (frozenset({(9, 'Y'), (2, 'Y'), (7, 'N'), (3, 'Y')}), 3, 'Y')],
     [(frozenset({(9, 'Y'), (2, 'Y'), (7, 'N'), (3, 'Y')}), 7, 'N'),
      (frozenset({(4, 'Y'), (0, 'Y'), (8, 'N'), (1, 'Y')}), 8, 'N')]]

It has 3 main components:

x[0] = [[(frozenset({(5, 'Y')}), 5, 'Y')]
x[1] = [(frozenset({(9, 'Y'), (2, 'Y'), (7, 'N'), (3, 'Y')}), 2, 'Y'), (frozenset({(4, 'Y'), (0, 'Y'), (8, 'N'), (1, 'Y')}), 4, 'Y'), (frozenset({(9, 'Y'), (2, 'Y'), (7, 'N'), (3, 'Y')}), 3, 'Y')];
x[2] = [(frozenset({(9, 'Y'), (2, 'Y'), (7, 'N'), (3, 'Y')}), 7, 'N'), (frozenset({(4, 'Y'), (0, 'Y'), (8, 'N'), (1, 'Y')}), 8, 'N')]].

They have different sizes. I would like to check if all the last components of the 3 lists meet a specific condition: 'Y' if all of them are 'Y'; 'N' if all of them are 'N'; or 'U' if there exists some 'Y' and some 'N' in each component. The result should in this example be something like: ['Y', 'Y', 'N'].

How can I solve this problem?

1 Answers

You want to apply a function to every element of your list x, and return a list of the results.

This can be done either with a list comprehension or with map:

def f(e):
  return 2*e

x = [1,2,3]

print([f(e) for e in x])
# [2, 4, 6]

print(list(map(f, x)))
# [2, 4, 6]

All you have to do now, is write this function f for your problem: here e is a list of triplets, and f should check if all third elements of the triplets are 'Y' or 'N'.

You can use all and any to check if all the elements or all the elements in a collection satisfy a condition:

collection = [2, 4, 6, 9]
print(all(n % 2 == 0 for n in collection))
# False

collection = [2, 4, 6, 8]
print(all(n % 2 == 0 for n in collection))
# True

Now, the elements in each sublist e of x are triplets (tuples with 3 elements). The first element of the triplet is a frozenset, which we don't care about. The second element of the triplet is a number, which we don't care about. And the third element of the triplet is either 'Y' or 'N', and those are the ones we're interested in.

def f(e):
  all_y = all(letter=='Y' for frozen,number,letter in e)
  all_n = all(letter=='N' for frozen,number,letter in e)
  lil_bit_o_both = (not all_y) and (not all_n)
  return 'Y' if all_y else ('N' if all_n else 'U')

x = [[(frozenset({(5, 'Y')}), 5, 'Y')],
     [(frozenset({(9, 'Y'), (2, 'Y'), (7, 'N'), (3, 'Y')}), 2, 'Y'),
      (frozenset({(4, 'Y'), (0, 'Y'), (8, 'N'), (1, 'Y')}), 4, 'Y'),
      (frozenset({(9, 'Y'), (2, 'Y'), (7, 'N'), (3, 'Y')}), 3, 'Y')],
     [(frozenset({(9, 'Y'), (2, 'Y'), (7, 'N'), (3, 'Y')}), 7, 'N'),
      (frozenset({(4, 'Y'), (0, 'Y'), (8, 'N'), (1, 'Y')}), 8, 'N')]]

result = list(map(f, x))
print(result)
# ['Y', 'Y', 'N']
Related