Advertisement
tokyoedtech

simple_solver_recursive.py

May 10th, 2020
1,279
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.40 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, o1 = "+", o2 = "+"):
  11.     # Define list of possible operators
  12.     operations = ["+", "-", "*", "/", "%"]
  13.    
  14.     # Base case
  15.     equation = "{} {} {} {} {}".format(x, o1, y, o2, z)
  16.     if eval(equation) == answer:
  17.         print("\n{} = {}".format(equation, answer))
  18.         return True
  19.        
  20.     if o1 == "%" and o2 == "%":
  21.         return False
  22.    
  23.     # Next operation    
  24.     if o2 == "%":
  25.         o1 = operations[operations.index(o1) + 1]
  26.         o2 = "+"
  27.     else:
  28.         o2 = operations[operations.index(o2) + 1]
  29.        
  30.     return solver(x, y, z, answer, o1, o2)
  31.    
  32. while True:
  33.     # Get the problem from the user
  34.     problem = input("\n> ")
  35.  
  36.     # Split into tokens
  37.     tokens = problem.split()
  38.    
  39.     if tokens[0] == "q":
  40.         break
  41.    
  42.     try:
  43.         # Convert to integers
  44.         x = int(tokens[0])
  45.         y = int(tokens[1])
  46.         z = int(tokens[2])
  47.         answer = int(tokens[-1])
  48.     except:
  49.         print("Invalid input")
  50.         continue
  51.  
  52.     solution_found = solver(x, y, z, answer)
  53.  
  54.     # Check if solution not found            
  55.     if not solution_found:
  56.         print("No solution found")
  57.            
  58. print("\nThe end")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement