简体   繁体   中英

Leetcode 3Sum TypeError: tuple object does not support item assignment

I'm getting a TypeError: tuple object does not support item assignment for line result_dict[t] = 0 . I want to check if my logic for 3Sum is correct, however, I'm not able to understand this issue.

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        i = 0
        result = []
        my_dict = dict()
        result_dict = ()
        
        for i in range(len(nums)):
            my_dict[nums[i]] = i
        
        for j in range(len(nums) - 1):
            target = nums[j]
            
            for i in range(j+1, len(nums)):
                y = -target - nums[i]
                key_check = tuple(sorted((nums[j], nums[i], y)))
                if key_check in result_dict:
                    continue
                if  my_dict.get(y) and my_dict[y]!=i and my_dict[y]!=j:
                    #result.append([nums[j], nums[i], y])
                    t = tuple(sorted((nums[j], nums[i], y)))
                    result_dict[t] = 0

        
        for key in result_dict.keys():
            result.append(list(key))
        return result
        #return list(set([ tuple(sorted(t)) for t in result ]))
            

An empty dictionary is created with empty curly brackets {} . Empty parentheses () will instead create a tuple which is basically an immutable list.

result_dict = {}

Will fix your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM