Reputation:
I try to test two to get set from list:
In first from each list create set and then union to result set or create one list and the return the set of list.
My result looks like no matter in which way to use, is it so? Or I have error logic in my research, or may be exist best way for such union?
import time
def set_from_set(*args):
l = set()
return set().union(*args)
def set_from_list(*args):
l = []
for larg in args:
l += larg
return set(l)
l1 = [x for x in range(1000000)]
l2 = [x for x in range(1000000)]
l3 = [x for x in range(1000000)]
dl1, dl2 = 0, 0
for x in range(100):
start = time.time()
set_from_list(l1, l2, l3)
dl1 += time.time() - start
for x in range(100):
start = time.time()
set_from_set(l1, l2, l3)
dl2 += time.time() - start
print(dl1, dl2)
result:
19.815733194351196 16.40732741355896
Upvotes: 0
Views: 5099
Reputation: 1201
Your problem lies in this function
def set_from_set(*args):
l= set()
for larg in args:
l.union(set(larg))
return l
the .union()
function returns a new set, it doesn't modify your old set in place.
Upvotes: 2