Here we discuss an interesting problem that has parallels with the work you are doing this week for Prelab 6 and Lab 6. There is nothing to turn in for this write-up – it is just helping us gain insights for the lab.
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 lecture
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 neccessary, re-prompt the
user. Since we we don’t know how many tries it will take, we will need a while
loop.
Here is some example code for this task:
existing_usernames = { "briggs", "schar", "smith" }
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"
existing_usernames.add(username)
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. You will want to
use a similar pattern in your lab to obtain a valid guess from the user.
Let’s think about the example for insert_letter
>>> insert_letter("a", "__n_n_", "banana")
'_anana'
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(underscored, solution):
return underscored == solution
Why does this work? Recall that the working word (here ‘underscored’) maintains the “state” of the unguessed letters (as underscores) and that winning is then the same as having replaced all of the underscores.