Earlier I mentioned a problem set in my computer science course to build the Hangman Game in Python. I am happy to report that I finished the game and it is working wonderfully.
I had also mentioned how the problem set required me to build a few helper functions before constructing the game loop. What excited me most about the development was the use of the set data structure in Python. Previously, I mentioned a helper function I built called word_guessed that returned True or False depending on if the player had guessed the secret word. I went into a discussion of imperative vs. declarative programming and how I prefered the declarative approach using sets in Python.
def word_guessed(secret_word, guesses): secret_word_letters = set(secret_word) return secret_word_letters.issubset(guesses) secret_word = 'secret' guesses = ['s', 'e', 'c', 'r', 'e', 't', 'a', 'z'] print word_guessed(secret_word, guesses) # True
More Python Set Goodness!
Well, I continued to use sets in Python in another function, because it brought out the essence of what the function is trying to do. It embraced this declarative approach to programming. The function returns a string of the available letters that the player can guess. This set of letters is all available letters minus the letters that have already been guessed. The function I built leverages sets once again in Python and is the following.
def get_available_letters(letters_guessed): ''' letters_guessed: list, what letters have been guessed so far returns: string, comprised of letters that represent what letters have not yet been guessed in alphabetical order. ''' all_letters = set(string.ascii_lowercase) available_letters = all_letters.difference(letters_guessed) return ''.join(sorted(list(available_letters)))
The cool part is the calculation of available_letters, which is the difference between the set of all lowercase letters and letters guessed. Python sets to the rescue!
I have been playing the game for fun after completing it for the problem set. The game loads 55909 words from a text file and randomly picks one as the secret word. Some of the words are tough to guess. I only get 8 missed guesses :)
Posted by Koder Dojo
I am learning the Python Programming Language in the open while attending several free online computer science, data structures, and algorithms classes over the summer. My articles will mention a lot of the problems sets and exercises in the classes and contain a lot of Python code and commentary. I hope it is useful and entertaining to others learning Python.