Skip to content

Instantly share code, notes, and snippets.

@qwqtoday
Created December 8, 2023 08:59
Show Gist options
  • Save qwqtoday/fa578bca7ca40fd62178dfb7aacbd2e2 to your computer and use it in GitHub Desktop.
Save qwqtoday/fa578bca7ca40fd62178dfb7aacbd2e2 to your computer and use it in GitHub Desktop.
from itertools import permutations
from typing import Optional
def add(n1, n2):
return n1+n2
def sub(n1, n2):
return n1-n2
def mul(n1, n2):
return n1*n2
def div(n1, n2):
return n1/n2
def calculate_24_point_answer(question: tuple[int, int, int, int]) -> Optional[str]:
operators = ('+', '-', '*', '/')
operators_fn = (add, sub, mul, div)
for n1, n2, n3, n4 in permutations(question):
for o1, o1_fn in zip(operators, operators_fn):
for o2, o2_fn in zip(operators, operators_fn):
for o3, o3_fn in zip(operators, operators_fn):
result = o3_fn(o2_fn(o1_fn(n1, n2), n3), n4)
if result == 24:
answer = f'{n1}{o1}{n2}{o2}{n3}{o3}{n4}'
return answer
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment