For our lab, we’re going to implement a text-based word guessing game similar to “Hangman”. You can read more about it on Wikipedia. This prelab will have you write a function that will be useful in coding your game.
For this lab and the prelab, you may work with a partner. You must both be present whenever you are working on the assignment material.
iterable
Recall from class that the set class has two “constructors”:
set() -> new empty set
object set(iterable) -> new set object
that is, two ways for creating new set objects. The first is used to create a new empty set. The second we’ve used with lists and strings to create new sets with some initial values.
The definition for this second constructor says that it takes as a parameter an
object that is iterable
. iterable
classes/objects provide a common
interface to iterate over their elements, independent of how those elements are
organized. For example, we can iterate over the items in an iterable
object
using a for loop:
for item in data:
print(item)
data
could be any iterable
value. Strings, lists and sets are all
iterable
, so can be used as the loop sequence (try it out if you’re curious).
Similarly, since the second set
constructor takes something that is
iterable
we could use any of those types to create a new set as well. This
should explain why when we create a set from a string, as in set("abcd")
, we
get a set consisting of the four characters in the string and not the string
itself.
Once you’re comfortable with this idea, write a function called
iterable_to_string
that takes a single parameter, an iterable
object, and
returns a string consisting of each item in the iterable
object converted to
a string using str()
and concatenated together, separated by a space. For
example, here are a few calls to this function:
>>> iterable_to_string("abcd")
'a b c d '
>>> iterable_to_string([4, 3, 2, 1])
'4 3 2 1 '
>>> iterable_to_string(set([4, 3, 2, 1]))
'1 2 3 4 '
Notice that all of the strings returned actually have a space at the end as well. Your function doesn’t have to do this, however, it’s fine if it does (an easy way to implement this function results in that behavior).
Submit your function as a Python file named prelab6.py to Gradescope as you would for a lab. You can submit multiple times, with only the most recent submission (before the due date) graded. Note that the tests performed by Gradescope are limited. Passing all of the visible tests does not guarantee that your submission correctly satisfies all of the requirements of the assignment.
If you worked with a partner, only one person needs to submit to Gradescope, but that person does need to add their partner’s name as shown in Gradescope documentation. Make sure both names are included in the comment at the top of the file.