0

This code snippet is one of posts in a LeetCode problem by fukuzawa_yumi

def splitArray(self, nums):
    d,n={nums[0]:[0]},len(nums)
    for i in range(1,n):
        nums[i]+=nums[i-1]
        if nums[i] not in d: d[nums[i]]=[i]
        else: d[nums[i]].append(i)
    for i in range(1,n-5):
        for k in d.get(nums[-1]-nums[i-1],[]):
            if i+3<k<n-1 and any(nums[i-1]+nums[j+1]==nums[k-1] for j in d.get(nums[i]+nums[i-1],[]) if i<j<k-2): return True
    return False

The nums[0]:[0], d: d[nums[i]]=[i] are unfamiliar to me and I can't find explanation online.

Please, reference me in the right direction and give a few examples for posterity.

  • 1
    The `d:` is the end of an `if`-clause... – csabinho Jan 11 '20 at 02:19
  • 1
    `nums[0]:[0]` is a key-value pair. `{nums[0]:[0]}` defines a dictionary where the value of `[0]` is assigned to the key `nums[0]`. Read up on Python dictionaries for details. – John Coleman Jan 11 '20 at 02:23
  • It can be somewhat confusing in the sense that `:` is heavily over-loaded in Python. `nums[0]:[0]` looks similar to but is really quite different from something like `nums[0:3]`, and both of these are quite different from something like `if d:` – John Coleman Jan 11 '20 at 02:36

2 Answers2

1
d,n={nums[0]:[0]},len(nums)

Is a somewhat ugly way of writing1:

d = {nums[0]: [0]}
n = len(nums)

It creates a dictionary d with a single item. The key is the first element in nums and the value is a one element list containing 0.

Later on, when you get to:

d[nums[i]] = [i]

This is a "replace-or-set" operation on the dictionary. The code is setting a dictionary item with key = nums[i] to a list with a single element whose value is i.

1In my subjective opinion :)

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
mgilson
  • 300,191
  • 65
  • 633
  • 696
1
d,n={nums[0]:[0]},len(nums)

What this line is doing is:

  • bind d to a dictionary formed a single element with the key nums[0] (first element in list nums) and value [0] (a list containing 0)
  • bind n to the length of the list nums

It is possible to combine the two assignments on one line like this in Python. Python will perform the assignment of the variables based on the order. It's the same as doing tuple expansion.

jignatius
  • 6,304
  • 2
  • 15
  • 30
  • I'd replace "assign" with "bind" here; as written, it sounds like the directions are reversed; `d` is being put in a `dict`, `n` is replacing the original length of the `list`, when in fact the `dict` is being "put into" `d`, and the length of the `list` is being put into `n`. "bind `d` to a dictionary" is less ambiguous. – ShadowRanger Jan 11 '20 at 02:33