Suppose we have a list of four numbers, each numbers are in range 1 to 9, in a fixed order. Now if we place the operators +, -, *, and / (/ denotes integer division) between the numbers, and group them with brackets, we have 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.
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
class Solution: def solve(self, nums): def recur(arr): answer =  for i in range(len(arr) - 1): pre, suf = recur(arr[: i + 1]), 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) return answer return 24 in recur(nums) ob = Solution() nums = [5, 3, 6, 8, 7] print(ob.solve(nums))
[5, 3, 6, 8, 7]