Alternate method of getting 'There is no solution' to print

Question:

Given integer coefficients of two linear equations with variables x and y, use brute force to find an integer solution for x and y in the range -10 to 10.

Is there an other way to get ‘There is no solution.’ to print just once? Making a count and adding +1 to that every time there is no solution in both of the lists works once the count has reached over 436. Is there a more efficient solution?

a = int(input())
b = int(input())
c = int(input())
d = int(input())
e = int(input())
f = int(input())
x = [-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = [-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
count = 0
for i in x:
    for o in y:
        if a*i + b*o == c and d*i + e*o == f:
            print('x =', i,',', 'y =', o)
        elif a*i + b*o != c and d*i + e*o !=f:
            count += 1
            if count > 436:
                print('There is no solution')
Asked By: Peraza99

||

Answers:

Just use a boolean variable and break out of the loop when you find a solution:

solved = False
for i in x:
    if solved:
        break
    for o in y:
        if a*i + b*o == c and d*i + e*o == f:
            print('x =', i,',', 'y =', o)
            solved = True
            break

if not solved:
    print('There is no solution')

And while we are at it, you can use ranges in Python instead of hard coding an array of all integers:

solved = False
for i in range(-10,11):
    if solved:
        break
    for o in range(-10,11):
        if a*i + b*o == c and d*i + e*o == f:
            print('x =', i,',', 'y =', o)
            solved = True
            break

if not solved:
    print('There is no solution')
Answered By: selbie

As a curiosity, you could use for else syntax too:

import itertools

for i, o in itertools.product(range(-10,11), range(-10,11)):
    if a*i + b*o == c and d*i + e*o == f:    
        print('x =', i,',', 'y =', o)
        break
else:
    print('There is no solution')
Answered By: kosciej16