我在課堂上有這個問題,給定兩個具有變數 x 和 y 的線性方程的整數系數,使用蠻力在 -10 到 10 的范圍內找到 x 和 y 的整數解。我的問題是,是否有替代方法得到“沒有解決方案。” 只列印一次?
每次兩個串列中都沒有解決方案時,我嘗試進行計數并在該計數中添加 1。一旦計數超過 436,這將起作用。但我想知道是否有更有效的解決方案。謝謝你的幫助!
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')
uj5u.com熱心網友回復:
出于好奇,您也可以使用for else語法:
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')
uj5u.com熱心網友回復:
只需使用布爾變數并在找到解決方案時跳出回圈:
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')
當我們這樣做時,您可以在 Python 中使用范圍,而不是硬編碼所有整數的陣列:
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')
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/533037.html