lundi 4 octobre 2021

While-loop with break under a condition in Python

I have a while-break-loop in Python that has to search for pairs with the letters [('H', 'Y')]. It should stop as soon as it finds a letter H (hybrid 'Y' and 'N') in frozensets (first element) and a 'Y' in the second element, and print 'No'.

def dt(z): 
    Y = all(letter=='Y' for number,letter in z)
    N = all(letter=='N' for number,letter in z)
    H = (not Y) and (not N)
    return 'Y' if Y else ('N' if N else 'H')

conj=[{(frozenset({(9,'N'), (3,'Y')}), 3,'Y'), (frozenset({(9,'Y'), (3,'N')}), 3,'Y')}, {(frozenset({(9,'Y'), (2,'Y')}), 3,'Y')}]

flag = 'Yes'
while flag == 'Yes':
    for i in conj:
        i = list(i)
        for j in i:
            s0 = list(j[0])
            t0 = list(j[-1])
            u0 = list(t0[-1])
            v0 = dt(s0)
            diag = list(zip(v0,u0))
            print(diag)
            if diag == [('H','Y')]:
                flag = 'No'
                break
    break
                
print(flag)

Although it deduces correctly that the flag is 'Yes' or 'No', it is searching all the sets. In the example above, it gives the answer:

[('H', 'Y')]
[('Y', 'Y')]
No

The [('Y','Y')] should not be printed, it should stop just after running (frozenset({(9,'Y'), (3,'N')}), 3,'Y'). It would be very useful for more complicated sets. How could I improve this? It should stop as soon as it finds a pair [('H','Y')] if there exists one.

Aucun commentaire:

Enregistrer un commentaire