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)
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)
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.