def solve(file): t = 0 t2 = 0 for line in file: nums = line.split() goal = int(nums[0].rstrip(":")) nums = [int(x) for x in nums[1:]] if viable(goal, nums): t += goal elif viable2(goal, nums): t2 += goal print(t) print(t+t2) def viable(goal, nums): candidates = [nums[0]] next = [] for x in nums[1:]: for n in candidates: for m in n*x, n+x: if m <= goal: next.append(m) next, candidates = candidates, next next.clear() #print(goal, nums, candidates, goal in candidates) return goal in candidates def viable2(goal, nums): candidates = [nums[0]] next = [] for x in nums[1:]: for n in candidates: for m in n*x, n+x, int(str(n)+str(x)): if m <= goal: #and m not in next: next.append(m) next, candidates = candidates, next next.clear() print(goal, nums, len(candidates), goal in candidates) return goal in candidates solve(open('sample1.in')) solve(open('input'))