4

I am attempting to find for which x and y values in the range(-10,10) the equation is satisfied and if no solution is found I am trying to output "No solution".

However, when attempting to output "No solution" I am either getting "No Solution" in every single iteration of it outputs "No solution" at the end regardless of if the for-loop is satisfied.

I am having trouble figuring out how to add in my print statement for when there is no solution.

Here is what I have thus far:

''' Read in first equation, ax + by = c '''
a = int(input())
b = int(input())
c = int(input())

''' Read in second equation, dx + ey = f '''
d = int(input())
e = int(input())
f = int(input())

for x in range(-10,10):
    for y in range(-10,10):
        if ((a*x) + (b*y)) == c and ((d*x) + (e*y)) == f:
            print(x, y)
            break
  • Why not just have a flag like `found_solution = False`, whose value you set to `True` inside the if statement, before breaking. – AMC Feb 10 '20 at 01:33

6 Answers6

5

You can use an else clause with a for loop. It is only executed if the for loop is not interrupted by a break.

for i in range(3):
    print(i)
else:
    print('hello')
# prints:
0
1
2
hello

for i in range(3):
    print(i)
    if i==1:
        break
else:
    print('world')
# prints:
0
1

Notice that world is not printed because the loop was interrupted by a break statement.

However, because you have 2 for loops, your break statement will only break the inner-most loop. To break both loops, you can use a flag to halt execution.

HALT = False
for x in range(-10,10):
    for y in range(-10,10):
        if ((a*x) + (b*y)) == c and ((d*x) + (e*y)) == f:
            print(x, y)
            HALT = True
            break
    if HALT:
        break
else:
    print('No solution')

Using itertools.product, you can dispense with the inner loop and the HALT flag.

from itertools import product


for x, y in product(range(-10, 10), repeat=2):
    if ((a*x) + (b*y)) == c and ((d*x) + (e*y)) == f:
        print(x, y)
        break
else:
    print('No solution')
chepner
  • 497,756
  • 71
  • 530
  • 681
James
  • 32,991
  • 4
  • 47
  • 70
  • 1
    Even simpler, don't have a second loop. `for x, y in product(range(-10, 10), repeat=2)):`. Then you don't need `HALT`, as `break` will take you straight to the `else` clause of the loop. – chepner Feb 09 '20 at 22:08
  • _"It is only executed if the for loop is not interrupted by a break"_ is easily the best explanation of for/else I've heard. I've been googling it for 4 years. – byxor Feb 10 '20 at 19:51
  • 1
    @byxor the way `for/else` works would be, in my opinion, clearer if Python had a `then` keyword. `for/then` would read as "do this for-loop, if you finsihed `then` do this block of code". – James Feb 10 '20 at 21:58
3

You can embedd your logic in function for better flow control (e.g. return statement will immediately step out of function)

'''Read in first equation, ax + by = c'''
a = int(input())
b = int(input())
c = int(input())

''' Read in second equation, dx + ey = f '''
d = int(input())
e = int(input())
f = int(input())


def find_solution():
    for x in range(-10, 10):
        for y in range(-10, 10):
            if ((a * x) + (b * y)) == c and ((d * x) + (e * y)) == f:
                return x, y

solution = find_solution()
if solution is not None:
    print(solution)
else:
    print("No solutions found")
Michal K
  • 335
  • 3
  • 12
1

You can just wrap your current code in a function and use return instead of break to skip both levels of loop:

def calc(a, b, c, d, e, f):
    for x in range(-10,10):
        for y in range(-10,10):
            if ((a*x) + (b*y)) == c and ((d*x) + (e*y)) == f:
                return x, y
    return "No solution"

print(calc(a, b, c, d, e, f))
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
1

Make the core "finding a solution" logic a function, and return either the first solution, or None. By the way, functions which don't have an explicit return <...> automatically return None.

Then, call this function and print either the result, or the error message.

I also took the liberty to extract the user-input section into a standalone function. And I wrote some -- I hope -- helpful comments to improve the Python a little.

def get_inputs():
    """ Gets the user input for six parameters. """
    ''' Read in first equation, ax + by = c '''
    a = int(input())
    b = int(input())
    c = int(input())

    ''' Read in second equation, dx + ey = f '''
    d = int(input())
    e = int(input())
    f = int(input())

    return (a, b, c, d, e, f)

def find_solution(a, b, c, d, e, f):
    """ Find's solution for ax + by == c and dx + ey == f
    for x, y in [-10, 10).

    Returns (x, y) or None
    """
    for x in range(-10,10):
        for y in range(-10,10):
            if ((a*x) + (b*y)) == c and ((d*x) + (e*y)) == f:
                return (x, y)
    return None  # Not necessary but explicit.


if __name__ == '__main__':  # This is good practice. More here: https://stackoverflow.com/questions/419163/
    a, b, c, d, e,f = get_inputs()
    solution = find_solution(a, b, c, d, e, f)
    if solution is not None:
        print(f"Solution found: x := {solution[0]}, y:= {solution[1]}") # These are f-strings and require Python 3.6.
        print("Solution found: x := {x}, y:= {y}".format(x = solution[0], y = solution[1])) # And this is the slightly older way of printing this.
    else:
        print("No solution could be found.")


Unapiedra
  • 15,037
  • 12
  • 64
  • 93
1

In Python 3.8, you can use the assignment expression and the any function to capture the values of x and y that satisfy the equation.

from itertools import product


if any((solution:=(x,y)) and a*x + b*y == c and d*x + e*y == f for x, y in product(range(-10, 10), repeat=2):
    print(solution)
else:
    print('No solution')
chepner
  • 497,756
  • 71
  • 530
  • 681
0

First, you need to define a boolean that is False to detect if there is an answer or not. When you get a solution turn it True so that you won't call print("No solution") even if you have an answer. Then you make sure you are on your last test you call an elif statement which would print No Solution. Here is the code:

''' Read in first equation, ax + by = c '''
a = int(input())
b = int(input())
c = int(input())

''' Read in second equation, dx + ey = f '''
d = int(input())
e = int(input())
f = int(input())
#Define boolean that will know if you printed a solution or not
isSolution = False

for x in range(-10,10):
    for y in range(-10,10):
        if ((a*x) + (b*y)) == c and ((d*x) + (e*y)) == f:
            #If you find a solution
            print(x, y)
            isSolution = True
            break
        elif (y==9 and x==9 and isSolution==False):
            #If there are no solutions
            print("No solution")

Tell me if there is a case where it prints a solution then prints "No solution" because I would like to fix my error. I hope the code above helps!

CCjump21
  • 68
  • 1
  • 7