Class 18: Set and Dictionary examples

Objectives for today

  1. Develop functions using sets and dictionaries

Choosing a valid username

I suspect everyone has had the experience of signing up for account at a website and being told that your preferred username is taken. Assume we have a list of existing usernames, let’s write some code to prompt the user to pick a username, and to keep prompting them until they pick a username that hasn’t already been taken.

Our first step is to think about what data structure would be best. Since we need to test for membership, a set is an efficient choice (recall from previous classes that membership operations are very fast on sets). Our second step is to think about what kind of loop we will need to prompt and, if necessary, re-prompt the user. Since we we don’t know how many tries it will take, we will need a while loop.

Try it out before looking at the code…

existing_usernames = { "mlinderman", "rlichenstein" }

username = input("Enter your desired username: ")
while username in existing_usernames:
    # Keep prompting for a new username as long as response
    # is in set of existing username
    print(username + " is already taken, pick a different name")
    username = input("Enter your desired username: ")
# At this point we know that the username is new (that is not
# in the set of existing usernames). Add it to the set so that
# it is now "taken"

print("You have successfully registered: " + username)

Notice the use of the while loop to re-prompt the user if the name they entered is taken. What do we know about username “after” the loop? That it must be novel (that is not previously taken). At that point we can now proceed with any operations that depend on our new username. I think you will want to use a similar pattern in your lab to obtain a valid guess from the user.

State (and the various properties derived from that state)

Let’s think about the example for insert_letter

>>> insert_letter("a", "__n_n_", "banana")

Here the current “underscored” word is a kind of state. What properties of the game are embedded in this state? For example, can we tell if the user has won? How?

Let’s develop a function has_won that takes the example hidden string as an argument and returns a boolean indicating if the user has won.

def has_won(working_word, guess_word):
    return working == guess_word

Why does this work? Recall that the working word maintains the “state” of the letters that haven’t been guessed (as underscores) and that winning is then the same as having replaced all of the underscores.