On Problem Set 5, #4, I'm having some problems. The update_hand function passed the test. However, when I run it with play_hand or play_game there is a problem. I have the program set up to use the update_hand function only when a valid word is entered. However, the update_hand function seems to be playing into effect even when the word is invalid, and when it IS valid, the update_hand is being used twice for some reason. Why?
When you are having trouble with a 'variable'/object, i.e. it is changing when it shouldn't be, a good place to start is to add print statements at strategic locations in the code to print the 'variable. That will let you see when/where it is changing. you should try that for yourself or... I tried it with your file and its evident what is happening: file attached.
had to get a different account, forgot old password. ok this still isnt making sense. i made hand = {'c':2,'a':2.'r':2} i inputted 'c'. It then went through 1, 8, 9, 5, 6. The hand changed to have one less 'c' at 9. How is it possible that the update_hand function is being used at 9, when it is directly listed under 2 and 2 is not being used? Thanks so much, I think I'm almost there and just missing something. If you know what it is exactly please let me know, because I've been trying for a long time
So yeah please help, and thanks :)
in is_valid_word, this line is the problem: new_hand = hand you have a dictionary object that hand points to. after that line new_hand and hand both point to the same dictionary object. you can see this with the print statement i put in - print 'new_hand IS hand', new_hand is hand so in is_valid_word, when you modify new_hand you are modifying the object that hand also points to... and you are using hand throughout the program. that's why you see it changed at print statement '9'. dictionary methods can be found here: http://docs.python.org/library/stdtypes.html#mapping-types-dict look at that and try the copy method: http://dpaste.com/559489/
there is something in one of the lectures about this phenomenon: here's a good explanation: http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables
thanks! it all works and makes sense now. and i get why it works that way too.
Join our real-time social learning platform and learn together with your friends!