WEEK 4 :: PYTHON CRASH COURSE :: STRING/LISTS/DICTIONARIES

¡Supera tus tareas y exámenes ahora con Quizwiz!

What's a major advantage of using dictionaries over lists?

It's quicker and easier to find a specific element in a dictionary (Because of their unordered nature and use of key value pairs, searching a dictionary takes the same amount of time no matter how many elements it contains)

If we have a string variable named Weather = "Rainfall", which of the following will print the substring or all characters before the "f"?

print(weather[:4])- Formatted this way, the substring preceding the character "f", which is indexed by 4, will be printed.

FOR MY NOTE: the meaning of [::3]

-'abcdefghijklm'[::3] # beginning to end, counting by 3 'adgjm' -'abcdefghijklm'[::-3] # end to beginning, counting down by 3 'mjgda'

Tuples and lists are very similar types of sequences. What is the main thing that makes a tuple different from a list?

Tuple is immutable (can't be changed)

The groups_per_user function receives a dictionary, which contains group names with the list of users. Users can belong to multiple groups. Fill in the blanks to return a dictionary with the users as keys and a list of their groups as values.

def groups_per_user(group_dictionary): user_groups = {} # Go through group_dictionary for group, users in group_dictionary.items(): # Now go through the users in the group for users in group_dictionary[group]: if users in user_groups: user_groups[users].append(group) else: user_groups[users] = [group] return(user_groups) ----------------------------- print(groups_per_user({"local": ["admin", "userA"], "public": ["admin", "userB"], "administrator": ["admin"] }))

FOR MY NOTE (on Practice Quiz week4:LISTS/Octal) - basically if the individual numbers are larger than values in key they write out the corresponding letters - ALL of them until nothing is left - similar to % function or floor division you look for remainder! 7 becomes rwx (7-4(r), 3-2(w), 1-1(x) 5 becomes r-x (5-4(r). 1 - 1(x) 5 gets no w because the 1 left over from 5-4 is less than 2. Instead it gets a "-". Anytime the remainder is less than what the value is you get a "-" mark instead of the letter that corresponds to its value.

value_letters = [(4,"r"),(2,"w"),(1,"x")] # this is a key with the pairs of value and letters for number in [int(n) for n in str(octal)]: # checking the individual numbers in octal like (755) and giving them variable as "number" for value, letter in value_letters: # iterating through values and letters in key if number >= value: result += letter number -= value # if the individual numbers (7,5,5) are larger than values in key (4,2,1) they write out the corresponding letters - ALL of them until nothing is left - similar to % function or floor division you look for remainder! 7 becomes rwx (7-4(r), 3-2(w), 1-1(x), 5 becomes r-x (5-4(r). 1 - 1(x) - no w because the 1 left over from 5-4 is less than 2. Anytime the remainder is less than what the number is you get a "-" mark instead of the letter else: result += "-" return result print(octal_to_string(755)) # Should be rwxr-xr-x

In Python, a dictionary can only hold a single value for a given key. To workaround this, our single value can be a list containing multiple values. Here we have a dictionary called "wardrobe" with items of clothing and their colors. Fill in the blanks to print a line for each item of clothing with each color, for example: "red shirt", "blue shirt", and so on.

wardrobe = {"shirt":["red","blue","white"], "jeans":["blue","black"]} for item, color in wardrobe.items(): for colorsub in color: print("{} {}".format(colorsub,item)) ------------ red shirt blue shirt white shirt blue jeans black jeans

Complete the code to iterate through the keys and values of the cool_beasts dictionary. Remember that the items method returns a tuple of key, value for each element in the dictionary.

cool_beasts = {"octopuses":"tentacles", "dolphins":"fins", "rhinos":"horns"} for key, value in cool_beasts.items(): print("{} have {}".format(key, value))

FOR MY NOTE: [::2]

return elements[::2] # USE STEP TO SKIP 2 #return elements[::-1] # USE NEGATIVE TO REVERSE THEN SKIP #return elements[::3] # USE STEP TO SKIP 3

The dict.update method updates one dictionary with the items coming from the other dictionary, so that existing entries are replaced and new entries are added. What is the content of the dictionary "wardrobe" at the end of the following code?

wardrobe = {'shirt': ['red', 'blue', 'white'], 'jeans': ['blue', 'black']} new_items = {'jeans': ['white'], 'scarf': ['yellow'], 'socks': ['black', 'brown']} wardrobe.update(new_items) --------------------------- answer : --------- {'shirt': ['red', 'blue', 'white'], 'jeans': ['white'], scarf': ['yellow'], 'socks': ['black', 'brown']}

Modify the first_and_last function so that it returns True if the first letter of the string is the same as the last letter of the string, False if they're different. Remember that you can access characters using message[0] or message[-1]. Be careful how you handle the empty string, which should return True since nothing is equal to nothing. def first_and_last(message): return False

def first_and_last(message): if len(message) == 0: return True elif message[0] == message[-1]: return True else: return False -------------------------- print(first_and_last("else")) print(first_and_last("tree")) print(first_and_last(""))

The add_prices function returns the total price of all of the groceries in the dictionary. Fill in the blanks to complete this function.

def add_prices(basket): # Initialize the variable that will be used for the calculation total = 0 # Iterate through the dictionary items for items, price in basket.items(): # Add each price to the total calculation # Hint: how do you access the values of # dictionary items? total += price # Limit the return value to 2 decimal places return round(total, 2) groceries = {"bananas": 1.56, "apples": 2.50, "oranges": 0.99, "bread": 4.59, "coffee": 6.99, "milk": 3.39, "eggs": 2.98, "cheese": 5.44} -------------------------------------- print(add_prices(groceries)) # Should print 28.44

Using the format method, fill in the gaps in the convert_distance function so that it returns the phrase "X miles equals Y km", with Y having only 1 decimal place. For example, convert_distance(12) should return "12 miles equals 19.2 km".

def convert_distance(miles): km = miles * 1.6 result = "{} miles equals {:.1f} km".format (miles,km) return result ---------------------------------- print(convert_distance(12)) # Should be: 12 miles equals 19.2 km print(convert_distance(5.5)) # Should be: 5.5 miles equals 8.8 km print(convert_distance(11)) # Should be: 11 miles equals 17.6 km

Modify the double_word function so that it returns the same word repeated twice, followed by the length of the new doubled word. For example, double_word("hello") should return hellohello10. def double_word(word): return

def double_word(word): return (word *2) + str(len(word*2)) ----------------------------------------------- print(double_word("hello")) # Should return hellohello10 print(double_word("abc")) # Should return abcabc6 print(double_word("")) # Should return 0

The email_list function receives a dictionary, which contains domain names as keys, and a list of users as values. Fill in the blanks to generate a list that contains complete email addresses (e.g. [email protected]).

def email_list(domains): emails = [] for email, users in domains.items(): for user in users: emails.append("{}@{}".format(user, email)) return(emails) ------------------ print(email_list({"gmail.com": ["clark.kent", "diana.prince", "peter.parker"], "yahoo.com": ["barbara.gordon", "jean.grey"], "hotmail.com": ["bruce.wayne"]}))

Let's use tuples to store information about a file: its name, its type and its size in bytes. Fill in the gaps in this code to return the size in kilobytes (a kilobyte is 1024 bytes) up to 2 decimal places.

def file_size(file_info): name, type, size= file_info return("{:.2f}".format(size/ 1024)) -------------------------------------- print(file_size(('Class Assignment', 'docx', 17875))) # Should print 17.46 print(file_size(('Notes', 'txt', 496))) # Should print 0.48 print(file_size(('Program', 'py', 1239))) # Should print 1.21

Using the "split" string method from the preceding lesson, complete the get_word function to return the {n}th word from a passed sentence. For example, get_word("This is a lesson about lists", 4) should return "lesson", which is the 4th word in this sentence. Hint: remember that list indexes start at 0, not 1.

def get_word(sentence, n): # Only proceed if n is positive if n > 0: words = sentence.split() # Only proceed if n is not more than the number of words if n <= len(words): return(words[n-1]) return("") ------------------------------ print(get_word("This is a lesson about lists", 4)) # Should print: lesson print(get_word("This is a lesson about lists", -4)) # Nothing print(get_word("Now we are cooking!", 1)) # Should print: Now print(get_word("Now we are cooking!", 5)) # Nothing

The group_list function accepts a group name and a list of members, and returns a string with the format: group_name: member1, member2, ... For example, group_list("g", ["a","b","c"]) returns "g: a, b, c". Fill in the gaps in this function to do that.

def group_list(group, users): members = group + ": " + ", ".join(users) return members -------------------- print(group_list("Marketing", ["Mike", "Karen", "Jake", "Tasha"])) # Should be "Marketing: Mike, Karen, Jake, Tasha" print(group_list("Engineering", ["Kim", "Jay", "Tom"])) # Should be "Engineering: Kim, Jay, Tom" print(group_list("Users", "")) # Should be "Users:"

The guest_list function reads in a list of tuples with the name, age, and profession of each party guest, and prints the sentence "Guest is X years old and works as __." for each one. For example, guest_list(('Ken', 30, "Chef"), ("Pat", 35, 'Lawyer'), ('Amanda', 25, "Engineer")) should print out: Ken is 30 years old and works as Chef. Pat is 35 years old and works as Lawyer. Amanda is 25 years old and works as Engineer. Fill in the gaps in this function to do that.

def guest_list(guests): result = [] for name,age,profession in guests: print("{} is {} years old and works as {}".format(name, age, profession)) --------------------- guest_list([('Ken', 30, "Chef"), ("Pat", 35, 'Lawyer'), ('Amanda', 25, "Engineer")]) --------------------------- """ Output should match: Ken is 30 years old and works as Chef Pat is 35 years old and works as Lawyer Amanda is 25 years old and works as Engineer """

Fill in the gaps in the initials function so that it returns the initials of the words contained in the phrase received, in upper case. For example: "Universal Serial Bus" should return "USB"; "local area network" should return "LAN" def initials(phrase): words = phrase.___ result = "" for word in words: result += ___ return ___

def initials(phrase): words = phrase.split() result = "" for word in words: result += word[0].upper() return result ----------------------- print(initials("Universal Serial Bus")) # Should be: USB print(initials("local area network")) # Should be: LAN print(initials("Operating system")) # Should be: OS

The is_palindrome function checks if a string is a palindrome. A palindrome is a string that can be equally read from left to right or right to left, omitting blank spaces, and ignoring capitalization. Examples of palindromes are words like kayak and radar, and phrases like "Never Odd or Even". Fill in the blanks in this function to return True if the passed string is a palindrome, False if not.

def is_palindrome(input_string): # We'll create two strings, to compare them new_string = input_string.replace(" ", "").lower() reverse_string = input_string.replace(" ",""). lower()[::-1] if new_string == reverse_string: return True return False ---------------------------- print(is_palindrome("Never Odd or Even")) # Should be True print(is_palindrome("abc")) # Should be False print(is_palindrome("kayak")) # Should be True

Fill in the gaps in the nametag function so that it uses the format method to return first_name and the first initial of last_name followed by a period. For example, nametag("Jane", "Smith") should return "Jane S."

def nametag(first_name, last_name): return("{} {}.".format(first_name, last_name[0])) ---------------------------------- print(nametag("Jane", "Smith")) # Should display "Jane S." print(nametag("Francesco", "Rinaldi")) # Should display "Francesco R." print(nametag("Jean-Luc", "Grand-Pierre")) # Should display "Jean-Luc G."

(EXPLANATION ON # 17-ABOVE) The permissions of a file in a Linux system are split into three sets of three permissions: read, write, and execute for the owner, group, and others. Each of the three values can be expressed as an octal number summing each permission, with 4 corresponding to read, 2 to write, and 1 to execute. Or it can be written with a string using the letters r, w, and x or - when the permission is not granted. For example: 640 is read/write for the owner, read for the group, and no permissions for the others; converted to a string, it would be: "rw-r-----" 755 is read/write/execute for the owner, and read/execute for group and others; converted to a string, it would be: "rwxr-xr-x" Fill in the blanks to make the code convert a permission in octal format into a string format.

def octal_to_string(octal): result = "" value_letters = [(4,"r"),(2,"w"),(1,"x")] # Iterate over each of the digits in octal for number in [int(n) for n in str(octal)]: # Check for each of the permissions values for value, letter in value_letters: if number >= value: result += letter number -= value else: result += "-" return result ------------------------------- print(octal_to_string(755)) # Should be rwxr-xr-x print(octal_to_string(644)) # Should be rw-r--r-- print(octal_to_string(750)) # Should be rwxr-x--- print(octal_to_string(600)) # Should be rw-------

The odd_numbers function returns a list of odd numbers between 1 and n, inclusively. Fill in the blanks in the function, using list comprehension. Hint: remember that list and range counters start at 0 and end at the limit minus 1.

def odd_numbers(n): return [x for x in range (0,n+1) if x%2 !=0] ------------------------------------------- print(odd_numbers(5)) # Should print [1, 3, 5] print(odd_numbers(10)) # Should print [1, 3, 5, 7, 9] print(odd_numbers(11)) # Should print [1, 3, 5, 7, 9, 11] print(odd_numbers(1)) # Should print [1] print(odd_numbers(-1)) # Should print []

Let's create a function that turns text into pig latin: a simple text transformation that modifies each word moving the first character to the end and appending "ay" to the end. For example, python ends up as ythonp

def pig_latin(text): say = "" # Separate the text into words temp =[] words = text.split() for word in words: # Create the pig latin word and add it to the list temp.append(word[1:] + word[0] +"ay") # Turn the list back into a phrase phrase=" ".join(temp) return phrase -------------------------- print(pig_latin("hello how are you")) # Should be "ellohay owhay reaay ouyay" print(pig_latin("programming in python is fun")) # Should be "rogrammingpay niay ythonpay siay unfay"

The replace_ending function replaces the old string in a sentence with the new string, but only if the sentence ends with the old string. If there is more than one occurrence of the old string in the sentence, only the one at the end is replaced, not all of them. For example, replace_ending("abcabc", "abc", "xyz") should return abcxyz, not xyzxyz or xyzabc. The string comparison is case-sensitive, so replace_ending("abcabc", "ABC", "xyz") should return abcabc (no changes made).

def replace_ending(sentence, old, new): # Check if the old string is at the end of the sentence if sentence.endswith(old): # Using i as the slicing index, combine the part # of the sentence up to the matched string at the # end with the new string i = sentence.rindex(old) new_sentence = sentence[:i]+new return new_sentence # Return the original sentence if there is no match return sentence ----------------------------------- print(replace_ending("It's raining cats and cats", "cats", "dogs")) # Should display "It's raining cats and dogs" print(replace_ending("She sells seashells by the seashore", "seashells", "donuts")) # Should display "She sells seashells by the seashore" print(replace_ending("The weather is nice in May", "may", "april")) # Should display "The weather is nice in May" print(replace_ending("The weather is nice in May", "May", "April")) # Should display "The weather is nice in April"

The skip_elements function returns a list containing every other element from an input list, starting with the first element. Complete this function to do that, using the for loop to iterate through the input list.

def skip_elements(elements): # Initialize variables new_list = [] i = 0 # Iterate through the list for i in range(len(elements)): # Does this element belong in the resulting list? if i%2 ==0: # Add this element to the resulting list new_list.append(elements[i]) # Increment i return new_list -------------- print(skip_elements(["a", "b", "c", "d", "e", "f", "g"])) # Should be ['a', 'c', 'e', 'g'] print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) # Should be ['Orange', 'Strawberry', 'Peach'] print(skip_elements([])) # Should be []

Try out the enumerate function for yourself in this quick exercise. Complete the skip_elements function to return every other element from the list, this time using the enumerate function to check if an element is on an even position or an odd position.

def skip_elements(elements): # code goes here new_list = [] for index, word in enumerate(elements): if index%2 ==0: new_list.append(word) return new_list --------------------------------------------------- print(skip_elements(["a", "b", "c", "d", "e", "f", "g"])) # Should be ['a', 'c', 'e', 'g'] print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) # Should be ['Orange', 'Strawberry', 'Peach']

Modify the student_grade function using the format method, so that it returns the phrase "X received Y% on the exam". For example, student_grade("Reed", 80) should return "Reed received 80% on the exam". def student_grade(name, grade): return ""

def student_grade(name, grade): return ("{} received {}% on the exam" .format(name, grade)) ----------------------------------- print(student_grade("Reed", 80)) print(student_grade("Paige", 92)) print(student_grade("Jesse", 85))

Given a list of filenames, we want to rename all the files with extension hpp to the extension h. To do this, we would like to generate a new list called newfilenames, consisting of the new filenames. Fill in the blanks in the code using any of the methods you've learned thus far, like a for loop or a list comprehension.

filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"] # Generate newfilenames as a list containing the new filenames # using as many lines of code as your chosen method requires. newfilenames= [file.replace('.hpp','.h') for file in filenames] print(newfilenames) ----------------------- # Should be ["program.c", "stdio.h", "sample.h", "a.out", "math.h", "hpp.out"]

The "toc" dictionary represents the table of contents for a book. Fill in the blanks to do the following: 1) Add an entry for Epilogue on page 39. 2) Change the page number for Chapter 3 to 24. 3) Display the new dictionary contents. 4) Display True if there is Chapter 5, False if there isn't.

toc = {"Introduction":1, "Chapter 1":4, "Chapter 2":11, "Chapter 3":25, "Chapter 4":30} toc ["Epilogue"] = 39 toc ["Chapter 3"] = 24 print(toc) print("Chapter 5" in toc) ----------------- ___ # Epilogue starts on page 39 ___ # Chapter 3 now starts on page 24 ___ # What are the current contents of the dictionary? ___ # Is there a Chapter 5?


Conjuntos de estudio relacionados

PBS Activity 2.1.1 - Activity 2.1.3

View Set

DECA Business Management & Administration Career Cluster Exam: BLTDM

View Set

Multiple Choice Questions for Final Exam

View Set

Statistics Ch. 7 Clarifying the Concepts

View Set

Chapters 1-10 Practice Exam Questions Final

View Set

Prep U chapter 17 preoperative Nursing Management

View Set

5. Property and Casualty Policies - General

View Set