Numerical Error when doing division for Case [3, 3, 8, 8]


  • 1
    L

    I am just trying to figure out a naive solution before I optimize the algorithm.

    It seems that I ran into numerical issue in Case [3,3,8,8]. I tried to debug and it seems it calculates 8/3 as 2.6666666666666665, which in turn gives some number very close to 24.0 but not exact for 8 / (3 - 8 / 3). What should I do in general to handle this kind of situation?

    class Solution(object):
        def judgePoint24(self, nums):
            """
            :type nums: List[int]
            :rtype: bool
            """
            return 24.0 in self.Possible_All_Perm(nums)
        
        def Possible_All(self, nums):
            if len(nums) == 1:
                return [float(nums[0])]
            result_temp = set()
            for i in range(len(nums)-1):
                list1 = self.Possible_All(nums[:i+1])
                list2 = self.Possible_All(nums[i+1:])
                result_temp.update(set([i + j for i in list1 for j in list2]))
                result_temp.update(set([i * j for i in list1 for j in list2]))
                result_temp.update(set([i - j for i in list1 for j in list2]))
                result_temp.update(set([i / j for i in list1 for j in list2 if j != 0.]))
            print(nums, result_temp)
            return list(result_temp)
        
        def Possible_All_Perm(self, nums):
            result = set()
            for i in itertools.permutations(nums):
                result.update(self.Possible_All(i))
            return list(result)
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.