pythonbrute-force

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


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')

Solution

  • 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')