#!/usr/bin/env python # coding: utf-8 # # 0. Data types, Boolean Variables, Expressions # ### a. Simple example with string functions # Write a function that shortens names as follows: # # lying Ted -> lyin' Ted # smiling Joe -> smilin' Joe # singing Sam -> singin' Sam # In[ ]: # Your function here # **Answer:** # def nicknames(name): # name, adj = name.split() # return name[:-1] + "' "+adj # ### b. Simple example with Booleans # Write a function that takes boolean values for whether it rains (`rain`) and whether I have an umbrella (`umbrella`), and returns True if I get wet (`wet`) # In[ ]: # Your function here # **Answer:** # def get_wet(rain, umbrella): # if rain==True and umbrella == False: # return True # return False # ### c. Simple example with expressions # Write a function to calculate the area of a circle given a radius. The formula for this is: # $$area \quad = \quad \pi \ r^2 $$ # # You can use the `math` function to get the value of `pi` # In[ ]: import math math.pi # Your function here # **Answer:** # def area(r): # a = math.pi * (r**2) # return a # # 1. Lists, Sets # ### a. List basics with string multiplication # Consider this list of letters: # # ['t', 'u', 'v', 'w', 'x', 'y', 'z'] # # Create the following list: # # ['t', 'uu', 'vvv', 'wwww', 'xxxxx', 'yyyyyy', 'zzzzzzz'] # # Hint: You can use `for` loops, a counter (`i+=1`), and string multiplication (`*`). # In[ ]: letters = ['t', 'u', 'v', 'w', 'x', 'y', 'z'] # In[ ]: i = 0 # for loop here # **Answer:** # new_letters = [] # i = 1 # for l in letters: # new_letters.append(i*l) # i+=1 # new_letters # Wrap your loop in a function so that you can produce this transformation for any list of input `letters` # In[ ]: # def multiply(letters): # function here # **Answer:** # def multiply(letters): # new_letters = [] # i = 1 # for l in letters: # new_letters.append(i*l) # i+=1 # return new_letters # In[ ]: # Test the function on a new input # multiply(['ant', 'bat', 'cat']) # ### b. List basics with fish # Consider this list of fish: # In[ ]: fish = ['one fish', 'two fish', 'red fish', 'blue fish', 'old fish', 'new fish'] # In[ ]: # Check if the entry 'red fish' is in the list # **Answer:** 'red fish' in fish # In[ ]: # Check if 'fish' is in the list # **Answer:** 'fish' in fish # In[ ]: # Use a for loop to print any item containing the letter 'o' # **Answer:** # for f in fish: # if 'o' in f: # print(f) # Create the list with only the first, descriptive word of each item in `fish`. That is, create: # # descriptives = ['one', 'two', 'red', 'blue', 'old', 'new'] # In[ ]: # Use a for loop to create a new list with only the first, descriptive word of each item in fish descriptives = [] # for loop here # **Answer:** # descriptives = [] # for f in fish: # descriptives.append(f.split()[0]) # print(descriptives) # ### c. Sets with MLK speeches # Consider these two excerpts from speeches by Martin Luther King Jr. # In[ ]: martin1 = '''Injustice anywhere is a threat to justice everywhere. We are caught in an inescapable network of mutuality, tied in a single garment of destiny. Whatever affects one directly, affects all indirectly. Never again can we afford to live with the narrow, provincial outside agitator idea. Anyone who lives inside the United States can never be considered an outsider anywhere within its bounds.''' martin2 = '''But we refuse to believe that the bank of justice is bankrupt. We refuse to believe that there are insufficient funds in the great vaults of opportunity of this nation. And so, we've come to cash this check, a check that will give us upon demand the riches of freedom and the security of justice.''' # In[ ]: # Make a unique list of words that appear in each speech. # Make your list case INsensitive so that "We" and 'we' are not separate words. # **Answer:** # martin1_words = set(martin1.lower().split()) # martin2_words = set(martin2.lower().split()) # In[ ]: # Find the words that are present in both speeches # **Answer:** # martin1_words & martin2_words # In[ ]: # Find the words that are present only in the first speech and not the second # **Answer:** # martin1_words - martin2_words # In[ ]: # Find the words that are present across either one or both speeches # **Answer:** # martin1_words | martin2_words # In[ ]: # Calculate the Jaccard similarity of the two excerpts (intersection / union) # **Answer:** # len(martin1_words & martin2_words) / len(martin1_words | martin2_words) # # 2. Dictionaries # ### a. Dictionaries and loops with Pasta # Consider the following list of Pastas: # In[ ]: pasta = { 'carbonara': { 'ingredients': ['eggs','bacon'], 'prep_time' : 20 }, 'ziti': { 'ingredients': ['ricotta', 'tomato', 'mozzarella'], 'prep_time' : 70 }, 'pesto': { 'ingredients': ['basil', 'garlic', 'lemon', 'pine nuts'], 'prep_time' : 30 }, 'bolognese': { 'ingredients': ['tomato', 'beef'], 'prep_time' : 90 }, 'alla vodka': { 'ingredients': ['vodka', 'tomato', 'cream'], 'prep_time' : 25 }, 'puttanesca': { 'ingredients': ['tomato', 'olive', 'onion'], 'prep_time' : 40 } } # In[ ]: # Write a loop to print the name of each pasta and its ingredients # **Answer:** # for k,v in pasta.items(): # print(f"Pasta {k:10s} is made with {v['ingredients']}") # In[ ]: # Write a loop to list all pastas with tomato as an ingredient # **Answer:** # tomato_pastas = [] # for k,v in pasta.items(): # if 'tomato' in v['ingredients']: # tomato_pastas.append(k) # print(f"The pastas with tomatoes are {tomato_pastas}") # In[ ]: # Write a loop to find the pasta with the longest prep time # **Answer:** # max_time = 0 # max_name = "" # for k,v in pasta.items(): # if v['prep_time']>max_time: # max_name = k # max_time = v['prep_time'] # print(f"The pasta with the longest prep time is {max_name}, with {max_time} minutes of cooking.") # In[ ]: # Write a loop to add "pasta" and "parmesan" to each ingredient list # **Answer:** # for k,v in pasta.items(): # pasta[k]['ingredients'] += ['pasta', 'parmesan'] # pasta # In[ ]: # Write a loop to get the unique ingredients we need to make all the pastas # **Answer:** # unique_ingredients =[] # for k,v in pasta.items(): # unique_ingredients += v['ingredients'] # unique_ingredients = set(unique_ingredients) # print("The unique ingredients are:", unique_ingredients) # ### b. Making a dictionary of words and counts # Consider the following song lyrics: # In[ ]: happy = """it might seem crazy what I'm 'bout to say sunshine she's here, you can take a break I'm a hot air balloon that could go to space with the air, like I don't care baby by the way huh, because I'm happy clap along if you feel like a room without a roof clap along if you feel like happiness is the truth clap along if you know what happiness is to you clap along if you feel like that's what you wanna do here come bad news, talking this and that well, give me all you got, and don't hold it back well, I should probably warn you I'll be just fine no offense to you, don't waste your time here's why because I'm happy""" # In[ ]: # How many lines are in the song? # **Answer:** # len(happy.split("\n")) # In[ ]: # Loop through the lines of the song and print all lines that ask us to "clap" # **Answer:** # for l in happy.split("\n"): # if "clap" in l: # print(l) # In[ ]: # How many words are in the song? # **Answer:** # len(happy.split()) # In[ ]: # What are the unique words? # **Answer:** # unique_words = set(happy.split()) # In[ ]: # Using a loop, create a dictionary of unique words and the count of times each word appears # **Answer:** # word_counts = {} # for w in unique_words: # word_counts[w] = happy.count(w) # word_counts # ### c. French-to-English translation # Consider this dictionary of French-to-English translations: # In[ ]: french ={ "avant-garde" : "ahead of its time", "vis-a-vis" : "regarding", "armoire" : "wardrobe", "dossier" : "file", "entree" : "main course", "impasse" : "deadlock", "liaison" : "connection", "panache" : "flamboyance", "pince-nez" : "spectacles", "pret-a-porter": "ready-to-wear", "prix-fixe" : "fixed-price", "sommelier" : "wine expert", "tete-a-tete" : "private conversation", "bric-a-brac" : "junk"} # Let's perform a few steps: # - We will find any French words in a sentence and print them # - Then, we will replace these words with English # - Finally, we will write a function to do this on any sentence # # Let's start with the following sentence. # In[ ]: sentence = "vis-a-vis the armoire , i said she could pick it up tomorrow , but she said she didn't want any more bric-a-brac" print(sentence) # - Step 1: Write a loop to check if a word is in the dictionary. # In[ ]: # Split sentence into a list of words # Loop over the words... # see if they are in the "french" dictionary # if they are, print their translation # **Answer:** # s = sentence.split() # Split the sentence into words # for w in s: # Loop over words # if w in french: # Check if w is in the "french" dictionary # print (french[w]) # If it is, print the translated value # - Step 2: Now, make a new sentence, `translated`, that has the French words replaced with their English counterpart # In[ ]: # Split sentence into a list of words # Initialize an empty translated sentence # Loop over the words... # see if they are in the "french" dictionary # if they are, translate them and add to translation # Otherwise, add to translated # **Answer:** # translated = [] # for w in s: # if w in french: # translated.append(french[w]) # else: # translated.append(w) # " ".join(translated) # - Step 3: Now, make a function to do this for any sentence # # In[ ]: # def translator(sentence): # ... # return translated # **Answer:** # def translate(s): # s = s.split() # translated = [] # for w in s: # if w in french.keys(): # translated.append(french[w]) # else: # translated.append(w) # translated = " ".join(translated) # return translated # - Step 4: Using a list, do this for all sentences in the following list # In[ ]: sentences = [ "in a tete-a-tete with my liaison i asked about the dossier , but he denied its existence ; we are at a real impasse", "as part of our prix-fixe meal , a sommelier will guide you in a choice of cabernets , followed by our entree of salmon", "you wear those pince-nez with such panache", "his design is too avant-garde for popular consumption ; it is definitely not suited for the pret-a-porter market"] # **Answer:** # for s in sentences: # print (translate(s)) # # 3. For loops # ### a. Tripling every third number # Write a function that triples every third number in a list. For example, if: # # input = [ 1, 2, 3, 4, 5, 6 , 7, 8, 9 ] # output = [ 1, 2, 9, 4, 5, 18, 7, 8, 27 ] # ^ ^ ^ # In[ ]: nums = [1, 2, 3, 4, 5, 6 , 7, 8, 9 ] # In[ ]: # Begin by writing a loop that identifies and prints every third number, using a loop counter. i = 0 # For loop # **Answer:** # i=0 # for n in nums: # if i%3 == 0: # print(n) # i+=1 # In[ ]: # Modify the loop to create a new list of numbers with every third number tripled. new_nums = [] # For loop # **Answer:** # i = 1 # new_nums = [] # for n in nums: # if i%3 == 0: # new_nums.append(n*3) # else: # new_nums.append(n) # i+=1 # new_nums # In[ ]: # Finally, wrap everything in a function # def triple_third(nums): # **Answer:** # def triple_third(nums): # i = 1 # new_nums = [] # for n in nums: # if i%3 == 0: # new_nums.append(n*3) # else: # new_nums.append(n) # i+=1 # return new_nums # In[ ]: # Test the function on original input # triple_third(nums) # In[ ]: # Test the function on a new input # triple_third([1,1,1,1,1,1,2,2,2]) # ### b. Pig latin # Create a function that converts a sentence into pig latin. Recall that pig latin takes the first letter of every sentence, puts it at the end of the word, and adds "ay". For example: # # "the quick brown fox" # becomes # # "hetay uickqay rownbay oxfay" # In[ ]: sentence = "the quick brown fox" # In[ ]: # Split the sentence into words # **Answer:** # s = sentence.split() # In[ ]: # Loop through the sentence, put the first letter last, and add 'ay' # **Answer:** # for w in s: # print(w[1:] + w[0] + 'ay') # In[ ]: # Store the results in a list and join it back together into a sentence # **Answer:** # latin = [] # for w in s: # latin.append(w[1:] + w[0] + 'ay') # " ".join(latin) # In[ ]: # Wrap the whole thing in a function # **Answer:** # def pig_latin(sentence): # s = sentence.split() # latin = [] # for w in s: # latin.append(w[1:] + w[0] + 'ay') # return " ".join(latin) # In[ ]: # Test the function # pig_latin("jumps over the lazy dog") # # 4. While loops # ### a. Simple examples # In[ ]: # Write a while loop that squares a number until it exceeds 1000. Start with x = 1.5 x=1.5 # While... # **Answer:** # while x<1000: # x = x**2 # print(x) # In[ ]: # Write a while loop that adds items from the list "colors" to a string until the string length exceeds 20 colors = ['red', 'yellow', 'green', 'blue', 'indigo', 'violet', 'chartreuse', 'magenta', 'gold'] s = '' # While... # **Answer:** # while len(s)<20: # s+=colors.pop() # s # In[ ]: # Write a loop that adds items from the list "colors" to a string until there is nothing left in the "colors" list # (e.g. the list is equal to []) colors = ['red', 'yellow', 'green', 'blue', 'indigo', 'violet', 'chartreuse', 'magenta', 'gold'] s = '' # While ... # **Answer:** # while colors!=[]: # s+=colors.pop() # s # In[ ]: # Write a loop that adds 5 to x and 6 to y until y exceeds x x = 10 y = 2 # While... # **Answer:** # while x>=y: # x+=5 # y+=6 # print(x,y) # ### b. Clocks # Write a loop to tell me if I am late. # - The clock will start in the morning, with some number of `hours` and `minutes` # - The loop should increment by one minute at a time. # - If `minutes` exceeds 60, 60 should be removed from minutes and `hours` should be increased by 1 # - It should print the time every 15 minutes # - If it is past noon, I am late # In[ ]: hours = 8 minutes = 53 # In[ ]: # Write a boolean statement to adjust hours and minutes, if minutes exceeds 60 # **Answer:** # if minutes>60: # minutes-=60 # hours+=1 # In[ ]: # Write a statement to print the time if minutes are an even multiple of 15 # **Answer:** # if minutes%15 == 0: # print(f"It's {hours}:{minutes:02.0f}") # In[ ]: # Write a function to print "You're late" if it's past noon # **Answer:** # if hours>=12: # print("You're late") # In[ ]: # Wrap everything in a while loop that increments minute by minute until it's noon # **Answer:** # while hours<12: # if minutes>=60: # minutes-=60 # hours+=1 # if minutes%15 == 0: # print(f"It's {hours}:{minutes:02.0f}") # if hours>=12: # print("You're late") # minutes+=1 # In[ ]: # Now, put all of *this* in a function that takes 'hours', 'minutes' as its argument # **Answer:** # def late(hours,minutes): # while hours<12: # if minutes>=60: # minutes-=60 # hours+=1 # if minutes%15 == 0: # print(f"It's {hours}:{minutes:02.0f}") # if hours>=12: # print("You're late") # minutes+=1 # In[ ]: # Test the function # late(6,32) # ### c. Casablanca # Consider the following list of classic quotes from the movie "Casablanca." # In[ ]: casablanca = [ "I'm shocked, shocked to find that gambling is going on in here!\n... Sir, you're winning.\n", "What is your nationality?\n... I'm a drunkard.\n... That makes Rick a citizen of the world.\n", "Here's to looking at you, kid.\n", "We'll always have Paris.\n", "Of all the gin joints in all the world... She had to walk into mine.\n", "Go ahead and shoot. You'll be doing me a favor.\n", "Louis, I think this is the beginning of a beautiful friendship.\n", "You know, Rick, I have many a friend in Casablanca, but somehow, just because you despise me, you are the only one I trust.\n", "Rick, I'm going to miss you. Apparently, you're the only one in Casablanca with less scruples than I.\n", "I came to Casablanca for the waters.\n... Waters?! We're in a DESERT!\nI was misinformed.\n", "Round up the usual suspects!\n", "Remember, this gun is pointed right at your heart.\n... That is my least vulnerable spot.\n", "You despise me don't you?\n...Well if I gave you any thought I probably would.\n", "Where were you last night?\n... That's so long ago, I don't remember.\nWill I see you tonight?\n...I never make plans that far ahead.\n"] # In this exercise, we will: # - Sample a random line from the movie # - Write a while loop to keep sampling until we find a quote we're looking for # - Wrap this inside a function # - Step 1: Print a random line from the movie. Remember that `random.choice()` can be used to sample items from the list # In[ ]: import random # In[ ]: # Get a random quote # **Answer:** # quote = random.choice(casablanca) # print(quote) # - Step 2: Test whether a given `word` is in a random quote. # In[ ]: # Check if word is in random quote word = "Rick" # **Answer:** # quote = random.choice(casablanca) # print(quote) # print(f"-- Is {word} in quote?") # print(word in quote) # - Step 3: Write a while loop with to keep returning random lines until a quote with `word` is found. # In[ ]: # Keep returning random lines until a quote with word is found word = "Rick" found = False #while found==False: # **Answer:** # found = False # while found==False: # quote = random.choice(casablanca) # print(quote) # if word in quote: # found=True # - Step 4: Use a loop counter to prevent an infinite loop; if more than 5 random samples have been taken and the word hasn't been found, break the loop # # In[ ]: # Add a loop counter word = "Rick" found = False i = 1 #while found==False: # **Answer:** # i = 1 # found = False # while found==False: # quote = random.choice(casablanca) # print(quote) # if word in quote: # found=True # if i>=5: # break # i+=1 # - Step 5: Wrap this inside a function. # - As an argument, your function should take the list `casablanca`, and the search word `word` # - It should return a random quote, or else the string "quote not found" if more than 5 iterations have been exceeded. # In[ ]: # Function to search for word in casablanca # def random_casablanca(casablanca, word): # **Answer:** # def random_casablanca(casablanca, word): # i = 1 # found = False # while found==False: # quote = random.choice(casablanca) # if word in quote: # found=True # return quote # if i>=5: # return "Quote not found" # i+=1 # In[ ]: # Test the function # result = random_casablanca(casablanca, "Casablanca") # print(result)