0

I have

print(list_games)
array([[77, 63],
       [94, 49],
        [58, 98],
       ...,
       [ 7,  0],
       [68, 22],
       [ 1, 32]], dtype=int64)

I need to print the first pair and their index, which satisfy the condition, but my code print all pairs. How can I fix it?

for i in range(len(list_games)):
    for j in range(len(list_games)):
        if list_games[i][0] + list_games[j][1] == 131:
            print(list_games[i][0], list_games[j][1])
            break

And I get:

77 54
94 37
58 73
51 80
80 51
74 57
66 65
61 70
87 44
40 91
Michael M.
  • 10,486
  • 9
  • 18
  • 34
  • You might find these two other threads interesting: https://stackoverflow.com/q/189645 and https://stackoverflow.com/q/653509 – Savir Oct 25 '22 at 22:33

2 Answers2

1

You can use a boolean to control if the first loop also should break or not.

loop = True
for i in range(len(list_games)):
    for j in range(len(list_games)):
        if list_games[i][0] + list_games[j][1] == 131:
            print(list_games[i][0], list_games[j][1])
            loop = False
            break
    if loop == False:
        break
BehRouz
  • 1,209
  • 1
  • 8
  • 17
0

The best option is to do it inside a function and return when the condition satisfies,

def match():
    for i in range(len(list_games)):
        for j in range(len(list_games)):
            if list_games[i][0] + list_games[j][1] == 131:
                return (list_games[i][0], list_games[j][1])

value = match()
print(value)

Execution:

In [1]: list_games = np.array([[77, 63], [94, 49], [58, 98],[ 7, 0], [68, 22], [ 1, 32]], dtype=np.int64)

In [2]: value = match()
   ...: print(value)
(68, 63)
Rahul K P
  • 15,740
  • 4
  • 35
  • 52