Advertisement
Guest User

Python 3 Befunge number thing

a guest
Apr 17th, 2016
40
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. import time
  2.  
  3. NUMBERS = '0123456789'
  4. NUMBERS_WITH_DUP = NUMBERS + ":"
  5. OPERATIONS = '+-/*'
  6.  
  7.  
  8. def solve(length):
  9. depth = (length - 1)/2
  10. solutions = {}
  11. for a in NUMBERS:
  12. solutions[int(a)] = [1, a]
  13. solutions = solve_depth(depth - 1, a, a, solutions)
  14. out_file = open('output_file.txt', 'w')
  15. for result, solution in sorted(solutions.items()):
  16. out_file.write(str(result)+'\t'+solution[1] + '\n')
  17. out_file.close()
  18.  
  19.  
  20. def solve_depth(depth, string, top_stack, solutions):
  21. for num in NUMBERS_WITH_DUP:
  22. for operation in OPERATIONS:
  23. eval_num = top_stack if num == ':' else num
  24. try:
  25. result = int(eval(top_stack + operation + eval_num))
  26. except:
  27. continue
  28. new_string = string + num + operation
  29. length = len(new_string)
  30. # If result is on the top of the stack and we already have a shorter or equivalent way to get there
  31. # Then there is no point in going further down the recursion.
  32. if (result not in solutions or solutions[result][0] > length) and result >= 0:
  33. solutions[result] = [length, new_string]
  34. if depth != 0:
  35. solutions = solve_depth(depth - 1, new_string, str(result), solutions)
  36. return solutions
  37.  
  38. start_time = time.time()
  39. solve(11)
  40. print("Finished in " + str(time.time() - start_time))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement