Intro to Data Structures
In our mad libs exercise we did some pretty cool things, but the game is pretty boring when the mad libs are the same every time. One way to solve this is building a list of possible madlibs.
Arrays, Lists, and Sets
Arrays, Lists, and Sets are just what they sound like, groups that can be iterated across or randomly accessed. Sets are special since they guarentee only 1 instance of each element. Lists can be:
first_names = ['John', 'John', 'John']
You can also use the random module to pick a random item from a list:
import random
first_names = ['John', 'Bob', 'Jim']
random_name = random.choice(first_names)
print(random_name)
Dictionaries
Dictionaries are key/value pairs. So I can store a mapping. For example if I want to store everyone’s weight by name it could be:
weights = dict()
weights['John'] = 205
print('John weighs {} pounds'.format(weights.get('John'))
Excercise
Augment the madlibs by selecting a random madlib from a list ever round. Couple of Input/Ouput syntax examples that might help:
madlibfile = open('madlibs.txt', 'r')
madlib = madlibfile.readline().strip()
while madlib:
madlibs.append(madlib)
madlib = madlibfile.readline().strip()