-2

I tried to change my original code with this set comprehension

next_states = {next_states | self.transition_function[(state, 
    input_value)] for state in e_closure_states}

But this code throws

TypeError: unhashable type: 'set'

Original code (working as expected). Also, it should be mentioned that self.transition_function[(state, input_value)] is set and that's why I am using union. Thanks in advance

for state in e_closure_states:
    next_states = next_states | self.transition_function[(state, input_value)]
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
M.Mar
  • 43
  • 9

1 Answers1

-2

The error TypeError: unhashable type: 'set' occurs because you're trying to add a set as an element of another set. As the error message implies, sets can only contain hashable elements, and sets themselves are unhashable.

I am not entirely sure that I understand what you’re trying to do, but tell me if this code produces the same thing as the for loop which you know is correct:

next_states = set.union(next_states, *(self.transition_function[(state, input_value)] for state in e_closure_states))

self.transition_function[(state, input_value)] is copied from your code. That’s inside of a generator, as indicated by the parentheses. The asterisk (*) unpacks the generator into the set.union() call. You can read more about that here.

AMC
  • 2,642
  • 7
  • 13
  • 35
  • 1
    Yes, but however I can do it without set comprehension. Just was curious why isn't working and if I had a mistake somewhere on my code. – M.Mar Nov 06 '19 at 04:45
  • @M.Mar Was my explanation of the error clear enough? Do you have any questions? – AMC Nov 06 '19 at 04:46
  • @BillChen What do you mean? OP was getting an error message in his code, and I explained why. The post doesn’t actually mention what he is trying to do, so finding a solution is a bit tough. I have an idea of what he might be doing though, so I guess i’ll go off of that. – AMC Nov 06 '19 at 05:03
  • Oh, sorry, I agree with you, I mean what is the solution here is depending on what the question is asking. I accidentally click the enter. :-) – Bill Chen Nov 06 '19 at 05:05
  • @M.Mar I wrote a solution. If you are still having trouble understanding why you got the error, I can explain it fully. I just didn’t do it yet because i’m typing on a phone, which is difficult. – AMC Nov 06 '19 at 05:34
  • @AlexanderCécile yea that actually worked. What is the * (self.transition_function[(state, input_value)]? Also, thank you! – M.Mar Nov 06 '19 at 20:21
  • @M.Mar I will update my answer to include an explanation of the code and some links, that way it’s more accessible. – AMC Nov 06 '19 at 22:40