Reputation: 1
I am doing leedcode problem and I found this solution online. I haven't understood line 2 lookup = {x[0]: i for i, x in enumerate(pieces)}
. Can anyone tell me how is it working? Also it will be cool if you can help me understanding whole program.
def canFormArray( arr, pieces):
lookup = {x[0]: i for i, x in enumerate(pieces)}
i = 0
while i < len(arr):
if arr[i] not in lookup:
return False
for c in pieces[lookup[arr[i]]]:
if i == len(arr) or arr[i] != c:
return False
i += 1
return True
arr = [15,88]
pieces = [[88],[15]]
p = canFormArray(arr,pieces)
print(p)
Upvotes: 0
Views: 34
Reputation: 2977
Google list comprehension.
lookup = {x[0]: i for i, x in enumerate(pieces)}
can be translated as
lookup = {} # init empty dict
for i, x in enumerate(pieces):
lookup[x[0]] = i
Upvotes: 1