Edit: I was using Jupyter notebook, I had two different scripts in a row while working, The script shown here is one, and the error shown here is from the other script. (mistake) Thanks for your time! I intentionally learned more though.
I’m trying to find an intersection between 10000 randomly generated lists of 6 elements numbers between 1 to 49 and a single list that I wrote myself also 1 to 49…
I tried using def like in the following script:
JavaScript
x
16
16
1
import random
2
lst1 = [7, 10, 21, 35, 48, 19]
3
lst2 = []
4
for i in range(10000):
5
r = random.sample(range(1, 50), 6)
6
lst2.append(r)
7
#HERE #(
8
def intersection(lst1, lst2):
9
lst3 = [value for value in lst1 if value in lst2]
10
return lst3 #)
11
12
13
#print(results)
14
print("------------")
15
print(Intersection(lst1, lst2))
16
but I get the following error:
JavaScript
1
16
16
1
---------------------------------------------------------------------------
2
TypeError Traceback (most recent call last)
3
<ipython-input-88-0caf870aa4e6> in <module>()
4
13 #print(results)
5
14 print("------------")
6
---> 15 print(Intersection(lst1, lst2))
7
8
<ipython-input-51-a4e2d32a8078> in Intersection(lst1, lst2)
9
7
10
8 def Intersection(lst1, lst2):
11
----> 9 return set(lst1).intersection(lst2)
12
10
13
11
14
15
TypeError: unhashable type: 'list'
16
Is there something I’m missing? I tried to look online but couldn’t find any solutions!
Advertisement
Answer
I changed list2 just to show that code is working you have some error in your code you can do something like that:
JavaScript
1
18
18
1
import random
2
3
lst1 = [7, 10, 21, 35, 48, 19]
4
lst2 = [6,7,10]
5
# for i in range(10000):
6
# r = random.sample(range(1, 50), 6)
7
# lst2.append(r)
8
9
10
# HERE #(
11
def intersection(lst1, lst2):
12
lst3 = [value for value in lst1 if value in lst2]
13
return lst3 # )
14
15
def Intersection(lst1, lst2):
16
return set(intersection(lst2,lst1))
17
print(Intersection(lst1, lst2))
18