Advertisement
Guest User

Untitled

a guest
Jun 19th, 2019
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.25 KB | None | 0 0
  1. def evaluate (method,running_sum):
  2. if eval(method) == target:
  3. if method not in list_methods:
  4. list_methods.append(method)
  5. print (f'Eval: {method}')
  6. return True
  7. if running_sum == target:
  8. if method not in list_methods:
  9. list_methods.append(method)
  10. print (f'Running sum: {method}')
  11. return True
  12.  
  13. def new_total (total,item,operation):
  14. if operation == "+": return total + item
  15. if operation == "-": return total - item
  16. if operation == "*" and total !=0:
  17. return total * item
  18. else:
  19. return ""
  20. if operation == "/" and total !=0 and item != 0:
  21. return total / item
  22. else:
  23. return ""
  24.  
  25. def solve (array,total=0,method="",list_method=[]):
  26. if len(array) == 0:
  27. return
  28.  
  29. for (index,item) in enumerate(array):
  30. #Set methods and totals to "":
  31. add_method, sub_method, mul_method, div_method = "", "", "", ""
  32. add_total, sub_total, mul_total, div_total = 0, 0, 0,0
  33.  
  34. #Assign methods and totals to a list:
  35. methods = [add_method, sub_method, mul_method, div_method]
  36. totals = [add_total, sub_total, mul_total, div_total]
  37. str_func = ["+", "-", "*", "/"]
  38.  
  39. #Create new array
  40. remaining = array[:index] + array[index+1:]
  41.  
  42. for index_1 in range (len(methods)):
  43. if method != "":
  44. methods[index_1] = method + str_func[index_1] + str(array[index])
  45. totals[index_1] = new_total(total,item,str_func[index_1])
  46. else:
  47. methods[index_1] = method + str(array[index])
  48. totals[index_1] = new_total(total,item,str_func[index_1])
  49. break
  50.  
  51. for index_2 in range (len(methods)):
  52. try:
  53. if evaluate(methods[index_2], totals[index_2]):
  54. return
  55. except Exception:
  56. pass
  57.  
  58. for index_3 in range (len(methods)):
  59. try:
  60. solve(remaining, total= totals[index_3],method= methods[index_3])
  61. except Exception:
  62. pass
  63.  
  64.  
  65. array = [100,9,10,40,1,3]
  66. target = 940
  67. print (f'Solutions for {array} to reach {target}')
  68. list_methods = []
  69. solve(array)
  70. if list_methods == []: print ("None")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement