Reputation: 233
S=set()
for i in range(1,100):
for j in range(1,100):
for k in range(1,100):
if i**2+j**2==k**2:
S.add(([i,j,k]))
print S
and the error is
TypeError Traceback (most recent call last)
<ipython-input-45-606e3083d711> in <module>()
4 for k in range(1,100):
5 if i**2+j**2==k**2:
----> 6 S.add(([i,j,k]))
7 print S
TypeError: unhashable type: 'list'
I just want to get all the distinct Pythagorean triples [for me (3,4,5)=(4,3,5)]. That's why I'm doing it with sets, but for some reason I can't append a set to my original set S...
Upvotes: 0
Views: 369
Reputation: 556
Instead of creating a set of lists, just sort the list and convert to tuples (to avoid dupes):
S=set()
for i in range(1,100):
for j in range(1,100):
for k in range(1,100):
if i**2+j**2==k**2:
# Notice I've changed squared brackets to round brackets for tuples, and sorted the list, so that duplicates are eliminated.
S.add(tuple(sorted([i,j,k])))
print(S)
`
I am assuming run time efficiency is not important for now.
Upvotes: 2
Reputation: 3744
The element of set need to be hashable, which means immutable, use tuple instead of list. Or you can use a frozenset.
For "get all the distinct Pythagorean triples [for me (3,4,5)=(4,3,5)].
", you can restrict the i
as smaller one, j
as larger one, sample code here:
S = set()
for i in range(1, 100):
# include i to support i=j case
for j in range(i, 100):
for k in range(1, 100):
if i ** 2 + j ** 2 == k ** 2:
S.add((i, j, k))
Hope that will help you.
Upvotes: 1