0

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.

Chr_8580
  • 71
  • 5

1 Answers1

0

I am not sure what your initial value of z parameter is but using z = [('H', 'Y'), ('Y', 'Y')]) and adjusting indentation of the final break appears to provide the expected behavior:

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)

z = [('H', 'Y'), ('Y', 'Y')]
dt(z)

[('H', 'Y')]
No
  • This one would not work in the case of an entry with no values that led to diag = ('H','Y') and flag would remain 'Yes'. It goes through an infinite loop. – Chr_8580 Oct 05 '21 at 10:20