Program to check whether we can form 24 by placing operators in python

Suppose we have a list of four numbers, each number is in range 1 to 9, in a fixed order. We need to place operators (+, -, *, /) between the numbers and group them with brackets to check whether it is possible to get the value 24 or not.

So, if the input is like nums = [5, 3, 6, 8, 7], then the output will be True, as (5 * 3) - 6 + (8 + 7) = 24.

Approach

We will use a recursive approach to generate all possible results by splitting the array at different points and applying all four operations between the left and right parts ?

  • Define a recursive function that takes an array
  • For each possible split point, recursively solve left and right subarrays
  • Apply all four operations (+, -, *, /) between results from left and right parts
  • Collect all possible results
  • Check if 24 exists in the final results

Example

class Solution:
    def solve(self, nums):
        def recur(arr):
            answer = []
            for i in range(len(arr) - 1):
                pre = recur(arr[:i + 1])
                suf = recur(arr[i + 1:])
                for k in pre:
                    for j in suf:
                        answer.append(k + j)
                        answer.append(k - j)
                        answer.append(k * j)
                        if j != 0:
                            answer.append(k // j)
            if len(answer) == 0 and len(arr) == 1:
                answer.append(arr[0])
            return answer
        return 24 in recur(nums)

# Test the solution
ob = Solution()
nums = [5, 3, 6, 8, 7]
print(ob.solve(nums))
True

How It Works

Let's trace through a smaller example with [4, 1, 8, 7] ?

class Solution:
    def solve(self, nums):
        def recur(arr):
            answer = []
            # Try all possible split points
            for i in range(len(arr) - 1):
                pre = recur(arr[:i + 1])
                suf = recur(arr[i + 1:])
                # Apply all operations between left and right results
                for k in pre:
                    for j in suf:
                        answer.append(k + j)
                        answer.append(k - j) 
                        answer.append(k * j)
                        if j != 0:
                            answer.append(k // j)
            # Base case: single element
            if len(answer) == 0 and len(arr) == 1:
                answer.append(arr[0])
            return answer
        return 24 in recur(nums)

# Test with different examples
ob = Solution()
test_cases = [[4, 1, 8, 7], [1, 1, 8, 8], [5, 3, 6, 8]]

for nums in test_cases:
    result = ob.solve(nums)
    print(f"nums = {nums}, can form 24: {result}")
nums = [4, 1, 8, 7], can form 24: True
nums = [1, 1, 8, 8], can form 24: True
nums = [5, 3, 6, 8], can form 24: False

Key Points

  • The algorithm generates all possible ways to combine numbers with operators
  • It uses integer division (//) to avoid floating-point precision issues
  • The recursive approach ensures all operator precedence combinations are considered
  • Base case returns the single element when array has only one number

Conclusion

This recursive solution systematically explores all possible operator placements and groupings to determine if 24 can be formed. The approach handles operator precedence by considering all ways to split and combine sub-expressions.

Updated on: 2026-03-25T13:01:56+05:30

193 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements