1

Saw this code on leetcode and don't get what it does or how it works. Paths is a list of lists.

def solution(paths):
    s = set(p[0] for p in paths)    
1
  • it's a function that take an 2-D array(arrays inside an array), then second line loop through 2-D array and take first element of the Nested array and store it in a set which is like an unordered list where elements can't be repeated then return final set Commented Oct 10, 2020 at 2:02

2 Answers 2

2

Ok not sure which part of the code you were referring to.

def solution(**paths**):          #1
    s = set(p[0] for p in paths)  #2

#1 creates a function called solution, that takes one argument (path)

#2 assigns a set to the variable s.

set( ) is a function creates a set object.

p[0] is the item you want from the forloop. and you are grabbing the first variable in each set that is in path

it can also be interpeted as:

def solution(paths):
    s = {}           # declare variable
    for item in path: # use forloop
        s.add(item[0]) #add the first element of each item in path (the set in path)
    print(s)

test_path = [ ['a','b','c'] , ['a','e','f'], ['g','h','i'] ]
solution(test_path)

notice in the results printed below that only one of the 'a' is added because a set only has unique variables

>>>{'g', 'a'}

You can do some Research on list comprehensions. I only started learning Python a few months ago myself. but i found this great video that I think explains the different types of comprehensions very well.

Python Tutorial: Comprehensions

Sign up to request clarification or add additional context in comments.

Comments

0

p is a list, and p[0] takes the first item in the sub-list, and this gets added to a set (i.e., duplicates are removed).

For example, if paths = [[1,2,3] , [1,3,4], [2,3,4]]

s = {1, 2} 

Note that function doesn't return anything since it does not have 'return'.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.