I wrote a code that should identify which of the elements of the sequence are equal to the sum of the elements of two different arrays, but it's wrong

Viewed 37

I am given two int arrays of different lentgh. Also I'm given a sequence of integers. I need to write a code, that prints "YES" for each element of the sequence if it can be obtained as a result of the sum of any element from first array and any element in second one. Otherwise it must print "NO" So, I wrote the code which seems working for me, but it fails on one of the test. I have no access to it, so i am asking here. Where did I go wrong?

N = int(input())
A = [int(x) for x in input().split()]
M = int(input())
B = [int(y) for y in input().split()]
K = int(input())
C = [int(z) for z in input().split()]
for z in C:
    flag = "NO"
    for i in range(N):
        for j in range(M):
            if z == A[i] + B[j]:
                flag = "YES"
                break
    print(flag)
1 Answers

To make your solution work you have to break out of the second for loop as well:

for c in C:
    flag = False
    for a in A:
        for b in B:
            if c == a + b:
                flag = True
                break
        if flag:
            break
    print('YES' if flag else 'NO')
Related