Advertisement
tokyoedtech

simple_solver.py

May 10th, 2020
1,068
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.24 KB | None | 0 0
  1. # Simple solver
  2. import os
  3. os.system("clear")
  4.  
  5. print("Simple Solver")
  6. print("Enter a problem in the following format using integers only: ")
  7. print("1 2 3 == 7")
  8. print("Type q to quit")
  9.  
  10. def solver(x, y, z, answer):
  11.     # Definte list of possible operators
  12.     operations = ["+", "-", "*", "/", "%"]
  13.  
  14.     # Assume no solution found
  15.     solution_found = False;
  16.  
  17.     # Iterate through all possibilities
  18.     for o1 in operations:
  19.         for o2 in operations:
  20.             equation = "{} {} {} {} {}".format(x, o1, y, o2, z)
  21.             if eval(equation) == answer:
  22.                 print("\n{} = {}".format(equation, answer))
  23.                 solution_found = True
  24.  
  25.     # Check if solution not found            
  26.     if not solution_found:
  27.         print("No solution found")
  28.  
  29. while True:
  30.     # Get the problem from the user
  31.     problem = input("\n> ")
  32.  
  33.     # Split into tokens
  34.     tokens = problem.split()
  35.    
  36.     if tokens[0] == "q":
  37.         break
  38.    
  39.     try:
  40.         # Convert to integers
  41.         x = int(tokens[0])
  42.         y = int(tokens[1])
  43.         z = int(tokens[2])
  44.         answer = int(tokens[-1])
  45.     except:
  46.         print("Invalid input")
  47.         continue
  48.  
  49.     solver(x, y, z, answer)
  50.            
  51. print("\nThe end")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement