打印“没有解决方案”的替代方法

问题描述 投票:0回答:2

给定带有变量 x 和 y 的两个线性方程的整数系数,使用强力法找到 x 和 y 在 -10 到 10 范围内的整数解。

是否有其他方法可以得到“没有解决方案。”只打印一次?一旦计数达到 436 以上,每次两个列表中都没有解决方案时,进行计数并加 +1。是否有更有效的解决方案?

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')
python brute-force
2个回答
2
投票

出于好奇,您也可以使用 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')

1
投票

只需使用布尔变量并在找到解决方案时跳出循环:

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')
© www.soinside.com 2019 - 2024. All rights reserved.