feasible = [] for x in range(8): for y in range(7): if 2 * x + y <= 14 and x + 3 * y <= 18: feasible.append((5 * x + 7 * y, x, y)) best = max(p for p, _, _ in feasible) winners = [(x, y) for p, x, y in feasible if p == best] assert winners == [(5, 4)] x, y = winners[0] result = {"x": x, "y": y, "profit": best} import json print(json.dumps(result, ensure_ascii=False, sort_keys=True))