I had this problem for class, 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. My question is, is there an alternate method to get 'There is no solution.' to print just once?
I've tried making a count and adding 1 to that count every time there is no solution in both of the lists. This works once the count has reached over 436. But I want to know if there is a more efficient solution. Thanks for any help!
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')
CodePudding user response:
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')
CodePudding user response:
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')