Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import time
- NUMBERS = '0123456789'
- NUMBERS_WITH_DUP = NUMBERS + ":"
- OPERATIONS = '+-/*'
- def solve(length):
- depth = (length - 1)/2
- solutions = {}
- for a in NUMBERS:
- solutions[int(a)] = [1, a]
- solutions = solve_depth(depth - 1, a, a, solutions)
- out_file = open('output_file.txt', 'w')
- for result, solution in sorted(solutions.items()):
- out_file.write(str(result)+'\t'+solution[1] + '\n')
- out_file.close()
- def solve_depth(depth, string, top_stack, solutions):
- for num in NUMBERS_WITH_DUP:
- for operation in OPERATIONS:
- eval_num = top_stack if num == ':' else num
- try:
- result = int(eval(top_stack + operation + eval_num))
- except:
- continue
- new_string = string + num + operation
- length = len(new_string)
- # If result is on the top of the stack and we already have a shorter or equivalent way to get there
- # Then there is no point in going further down the recursion.
- if (result not in solutions or solutions[result][0] > length) and result >= 0:
- solutions[result] = [length, new_string]
- if depth != 0:
- solutions = solve_depth(depth - 1, new_string, str(result), solutions)
- return solutions
- start_time = time.time()
- solve(11)
- print("Finished in " + str(time.time() - start_time))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement