1

can you please tell me what's the difference between

 mp = [{}] * n

and

 mp = [{} for i in range(n)]

also, what's the right way to do it.

I'm using it to solve the below algo, but only initialization with range works.

def longestArithSeqLength(self, nums: List[int]) -> int:
        result = 2
        n = len(nums)
        #mp = [{}] * n
        mp = [{} for i in range(n)]
        print(mp, dp)
        for x in range(1,len(nums)):
            for y in range(x):
                diff = nums[x] -nums[y]
                if diff in mp[y]:
                    curr = mp[y][diff]
                    mp[x][diff] = curr +1
                else:
                    mp[x][diff] = 2
                result = max(result,mp[x][diff])
            
        return result
  • 2
    `mp = [{}] * n` creates a single dictionary and then creates a list with `n` references to that single dict. `mp = [{} for i in range(n)]` creates a a bunch of unique dictionaries in a list. Usually you want the latter. – tdelaney Sep 25 '21 at 04:09

0 Answers0