Search code examples
pythonfor-loopcollectionsnested-loopsnested-lists

Findings letters that match in every sublist


candidates = ['A', 'B', 'C', 'D']

If a candidate appears in every sublist at least once they must be returned

listOfData = [['B','C','B','A'], #D is no longer a candidate
              ['B', 'C', 'B', 'D'], #A is no loner a candidate
              ['A','D','C','B'], # B and C are still candidates
              ['D', 'C', 'B', 'A']] # B and C are solid matches!

In this case the matches are [B,C]

I'm having trouble keeping track of the candidate that appears in every sublist at least once.

matches =[]           
def lettersThatMatchInEverySublist():
    i=0
    for candidate in candidates:
        for sublist in listOfData:
            for char in sublist:
                pass
        if char == candidate:
            matches.append(candidate)

    return matches

Solution

  • Easiest way - with sets

    >>> valid_vals = tuple(set(row) for row in listOfData)
    >>> candidates = set(['A', 'B', 'C', 'D'])
    >>> for validator in valid_vals:
        candidates &= validator
    
    
    >>> candidates
    set(['C', 'B'])