diff --git a/code/LeetCode/24Game/24Game b/code/LeetCode/24Game/24Game new file mode 100644 index 0000000000..bb885d70e2 --- /dev/null +++ b/code/LeetCode/24Game/24Game @@ -0,0 +1,54 @@ + +''' +24 Game +You are given an integer array cards of length 4. You have four cards, each containing a number in the range [1, 9]. You should arrange the numbers on these cards in a mathematical expression using the operators ['+', '-', '*', '/'] and the parentheses '(' and ')' to get the value 24. + +You are restricted with the following rules: + +The division operator '/' represents real division, not integer division. +For example, 4 / (1 - 2 / 3) = 4 / (1 / 3) = 12. +Every operation done is between two numbers. In particular, we cannot use '-' as a unary operator. +For example, if cards = [1, 1, 1, 1], the expression "-1 - 1 - 1 - 1" is not allowed. +You cannot concatenate numbers together +For example, if cards = [1, 2, 1, 2], the expression "12 + 12" is not valid. +Return true if you can get such expression that evaluates to 24, and false otherwise.''' + +''' +Important Note: This code is recycled from a best practice solution on LeetCode. There is no licensing +that permits the reuse of this code +''' + +from itertools import permutations +import operator + +def judgePoint24(cards): + # Operators for calculations + ops = [operator.add, operator.sub, operator.mul, operator.truediv] + + # Check if any sequence of operations can result in 24 + def dfs(nums): + if len(nums) == 1: # Base case: if only one number is left + return abs(nums[0] - 24) < 1e-6 # Check if it's close to 24 + + for i in range(len(nums)): + for j in range(len(nums)): + if i != j: + for op in ops: + # Create a new list of numbers without i and j + nums_left = [nums[k] for k in range(len(nums)) if k != i and k != j] + # Try applying the operator to nums[i] and nums[j] + try: + result = op(nums[i], nums[j]) + nums_left.append(result) + if dfs(nums_left): # Recurse with the new list + return True + nums_left.pop() # Backtrack + except ZeroDivisionError: + continue + return False + + # Try all permutations of the four numbers + for nums in permutations(cards): + if dfs(list(nums)): + return True + return False \ No newline at end of file