Skip to content

Instantly share code, notes, and snippets.

@kenchou
Last active November 4, 2023 10:41
Show Gist options
  • Select an option

  • Save kenchou/c465f67e925db6531eb0e8e44686b9b9 to your computer and use it in GitHub Desktop.

Select an option

Save kenchou/c465f67e925db6531eb0e8e44686b9b9 to your computer and use it in GitHub Desktop.
calculate 24
import click
from decimal import Decimal
from itertools import permutations, product
def calculate24(nums):
ops = list(product(["+", "-", "*", "/"], repeat=3)) # 所有可能的运算符组合
num_perms = list(permutations([Decimal(n) for n in nums])) # 所有可能的数字组合
result = False
solutions = []
for nums in num_perms:
for op in ops:
# 构建并计算表达式
exprs = [
f"{nums[0]} {op[0]} {nums[1]} {op[1]} {nums[2]} {op[2]} {nums[3]}",
f"( {nums[0]} {op[0]} {nums[1]} ) {op[1]} {nums[2]} {op[2]} {nums[3]}",
f"( {nums[0]} {op[0]} {nums[1]} {op[1]} {nums[2]} ) {op[2]} {nums[3]}",
f"{nums[0]} {op[0]} ( {nums[1]} {op[1]} {nums[2]} ) {op[2]} {nums[3]}",
f"{nums[0]} {op[0]} ( {nums[1]} {op[1]} {nums[2]} {op[2]} {nums[3]} )",
f"{nums[0]} {op[0]} {nums[1]} {op[1]} ( {nums[2]} {op[2]} {nums[3]} )",
]
for expr in exprs:
try:
if eval(expr) == 24:
result = True
solutions.append(expr)
except ZeroDivisionError:
continue
return result, solutions
@click.command()
@click.argument("nums", nargs=-1)
def main(nums):
print(f"{nums=}")
result, solutions = calculate24(nums) # 输出:True
if result:
for solution in solutions:
print(solution)
else:
print("No solution")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment