<jupyter_start><jupyter_text>Week 4 - Strings  Week 4 - What is a string? - Desafio<jupyter_code>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<jupyter_output><empty_output><jupyter_text>Week 4 - The Parts of a String - Exemplo<jupyter_code>name = "Jaylen"

print(name[1])
print(name[0])
print(name[5])
print(name[-1])
print(name[-2])
print(name[6])<jupyter_output><empty_output><jupyter_text>Week 4 - The Parts of a String - Desafio<jupyter_code>def first_and_last(message):
    if message != "" and (message[-1] != message[0]):
        return False
    else:
        return True

print(first_and_last("else"))
print(first_and_last("tree"))
print(first_and_last(""))<jupyter_output><empty_output><jupyter_text>Week 4 - The Parts of a String - Exemplo<jupyter_code>color = "Pineapple"

print(color[1:4])
print(color[:4])
print(color[4:])<jupyter_output><empty_output><jupyter_text>Week 4 - Creating New Strings - Exemplo<jupyter_code>message = "A kong string with a silly typo"
# String é imutável<jupyter_output><empty_output><jupyter_text>Week 4 - Creating New Strings - Desafio<jupyter_code>word = "supercalifragilisticexpialidocious"
print(word.index("x"))<jupyter_output><empty_output><jupyter_text>Week 4 - Creating New Strings - Exemplo<jupyter_code>pets = "Cats & Dogs"

print(pets.index("&"))
print(pets.index("C"))
print(pets.index("Dog"))
print(pets.index("s"))
#print(pets.index("x"))
print()

print("Dragons" in pets)
"Cats" in pets<jupyter_output><empty_output><jupyter_text>Week 4 - Creating New Strings - Exemplo<jupyter_code>def replace_domain(email, oldDomain, newDomain):
    if "@" + oldDomain in email:
        index = email.index("@" + oldDomain)
        newDomain = email[:index] + "@" + newDomain
        return newDomain
    return email


replace_domain("<EMAIL>", "seconci.com", "zarpo.com")<jupyter_output><empty_output><jupyter_text>Week 4 - More String Methods"Mountains".upper()  Deixa Maiusculo"Mountains".lower()  Deixa Minusculo" yes ".strip()  Retira os espaços da String" yes ".lstrip()  Retira os espaços a esquerda da String" yes ".rstrip()  Retira os espaços a direita da String"The number of times e occurs in this string is 4".count("e")  Conta quantas Substrings possui a String"Forest".endswith("rest")  Retorna(True/False) se a string acaba com a substring"12345".isnumeric()  Retorna(True/False) se a tring contem apenas numerico"Orange".isalpha()  Retorna(True/False) se a string contem apenas letras do alfabeto Week 4 - More String Methods - Join / Split" ".join(["This", "is", "a", "phrase", "joined", "by", "spaces"])'This is a phrase joined by spaces'"...".join(["This", "is", "a", "phrase", "joined", "by", "triple", "dots"])'This...is...a...phrase...joined...by...triple...dots'"This is another example".split()['This', 'is', 'another', 'example']<jupyter_code># Week 4 - More String Methods - Desafio

def initials(phrase):
    words = phrase.split()
    result = ""
    for word in words:
        result += word[0]
    return result.upper()

print(initials("Universal Serial Bus")) # Should be: USB
print(initials("local area network")) # Should be: LAN
print(initials("Operating system")) # Should be: OS
# Week 4 - Formatting Strings - Exemplo

name = "Manny"
number = len(name) * 3

print("Hello {}, your lucky number is {}".format(name, number))
#Hello Manny, your lucky number is 15

print("Your lucky number is {number}, {name}".format(name=name, number=len(name)*3))
#Your lucky number is 15, Manny
# Week 4 - Formatting Strings - Desafio

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))
# Week 4 - Formatting Strings - Exemplo

price = 7.5
with_tax = price * 1.09

print(price, with_tax)
#7.5 8.175

print("Base price: ${:.2f}. With Tax: ${:.2f}".format(price, with_tax))
#Base price: $7.50. With Tax: $8.18
# Week 4 - Formatting Strings - Exemplo

def to_celsius(x):
    return (x-32)*5/9

for x in range(0, 101, 10):
    print("{:>3} F | {:>6.2f} C".format(x, to_celsius(x)))<jupyter_output><empty_output><jupyter_text>Cheat Sheet: String Reference  Most common string operations and string methods. String operationslen(string) Returns the length of the stringfor character in string Iterates over each character in the stringif substring in string Checks whether the substring is part of the stringstring[i] Accesses the character at index i of the string, starting at zerostring[i:j] Accesses the substring starting at index i, ending at index j-1. If i is omitted, it's 0 by default. If j is omitted, it's len(string) by default. String methodsstring.lower() / string.upper() Returns a copy of the string with all lower / upper case charactersstring.lstrip() / string.rstrip() / string.strip() Returns a copy of the string without left / right / left or right whitespacestring.count(substring) Returns the number of times substring is present in the stringstring.isnumeric() Returns True if there are only numeric characters in the string. If not, returns False.string.isalpha() Returns True if there are only alphabetic characters in the string. If not, returns False.string.split() / string.split(delimiter) Returns a list of substrings that were separated by whitespace / delimiterstring.replace(old, new) Returns a new string where all occurrences of old have been replaced by new.delimiter.join(list of strings) Returns a new string with all the strings joined by the delimiter  Using the format() method "base string with {} placeholders".format(variables)example = "format() method"formatted_string = "this is an example of using the {} on a string".format(example)print(formatted_string)"""Outputs:this is an example of using the format() method on a string"""If the placeholders indicate a number, they’re replaced by the variable corresponding to that order (starting at zero). "{0} {1}".format(first, second)first = "apple"second = "banana"third = "carrot"formatted_string = "{0} {2} {1}".format(first, second, third)print(formatted_string)"""Outputs:apple carrot banana"""If the placeholders indicate a field name, they’re replaced by the variable corresponding to that field name. This means that parameters to format need to be passed indicating the field name. "{var1} {var2}".format(var1=value1, var2=value2)"{:exp1} {:exp2}".format(value1, value2)If the placeholders include a colon, what comes after the colon is a formatting expression. See below for the expression reference. {:d} integer value'{:d}'.format(10.5) → '10'Formatting expressionsExpr | Meaning | Example{:d} | integer value | '{:d}'.format(10.5) → '10'{:.2f} | floating point with that many decimals | '{:.2f}'.format(0.5) → '0.50'{:.2s} | string with that many characters | '{:.2s}'.format('Python') → 'Py'{:<6s} | string aligned to the left that many spaces | '{:<6s}'.format('Py') → 'Py    '{:>6s} | string aligned to the right that many spaces | '{:>6s}'.format('Py') → '    Py'{:^6s} | string centered in that many spaces | '{:^6s}'.format('Py') → '  Py  '  Quiz Strings: Week 4<jupyter_code>#Pergunta 1
#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 = ""
	reverse_string = ""
	# Traverse through each letter of the input string
	for word in input_string:
		# Add any non-blank letters to the 
		# end of one string, and to the front
		# of the other string. 
		if word != " ":
			new_string += word 
			reverse_string = word + reverse_string
	# Compare the strings
	if new_string.lower() == reverse_string.lower():
		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
#Pergunta 2
#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
#Pergunta 4
#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 "<NAME>."

def nametag(first_name, last_name):
	return("{}.".format(first_name + " " + last_name[0]))

print(nametag("Jane", "Smith")) 
# Should display "<NAME>." 
print(nametag("Francesco", "Rinaldi")) 
# Should display "<NAME>." 
print(nametag("Jean-Luc", "Grand-Pierre")) 
# Should display "<NAME>." 
#Pergunta 5
#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 = len(sentence) - len(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"<jupyter_output><empty_output><jupyter_text>Week 4 - List   week 4 - List: What is a list? - Exemplox = ["Now", "we", "are", "cooking!"]type(x)listprint(x)['Now', 'we', 'are', 'cooking!']len(x)4"are" in xTrue"Today" in xFalseprint(x[0])Nowprint(x[3])cooking!x[1:3]['we', 'are']x[:2]['Now', 'we']x[2:]['are', 'cooking!']<jupyter_code># Week 4 - What is a list? - Desafio

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<jupyter_output><empty_output><jupyter_text>Week 4 - Modifying the Contents of a List - Exemplofruits = ["Pineapple", "Banana", "Apple", "Melon"]fruits.append("Kiwi")print(fruits)['Pineapple', 'Banana', 'Apple', 'Melon', 'Kiwi']fruits.insert(0, "Orange")print(fruits)['Orange', 'Pineapple', 'Banana', 'Apple', 'Melon', 'Kiwi']fruits.insert(25, "Peach")print(fruits)['Orange', 'Pineapple', 'Banana', 'Apple', 'Melon', 'Kiwi', 'Peach']fruits.remove("Melon")print(fruits)['Orange', 'Pineapple', 'Banana', 'Apple', 'Kiwi', 'Peach']fruits.pop(3)'Apple'print(fruits)['Orange', 'Pineapple', 'Banana', 'Kiwi', 'Peach']fruits[2] = "Strawberry"print(fruits)['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach']  Week 4 - Modifying the Contents of a List - Desafio<jupyter_code>def skip_elements(elements):
	# Initialize variables
	new_list = []
	i = 0

	# Iterate through the list
	for word in elements:
		# Does this element belong in the resulting list?
		if i % 2 == 0:
			# Add this element to the resulting list
			new_list.append(word)
		# Increment i
		i += 1

	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 []<jupyter_output><empty_output><jupyter_text>Week 4 - List and Tuples - Exemplo<jupyter_code>def convert_seconds(seconds):
    hours = seconds // 3600
    minutes = (seconds - hours*3600) // 60
    remain_seconds = seconds - hours * 3600 - minutes * 60
    return hours, minutes, remain_seconds

result = convert_seconds(5000)
type(result)
#tuple
print(result)
hours, minutes, seconds = result
print(hours, minutes, seconds)
hours, minutes, seconds = convert_seconds(1000)
print(hours, minutes, seconds)<jupyter_output><empty_output><jupyter_text>Week 4 - List and Tuples - Desafio<jupyter_code>def file_size(file_info):
	name, typeFile, 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<jupyter_output><empty_output><jupyter_text>Week 4 - Iterating over Lists and Tuples - Exemplo<jupyter_code>animals = ["Lion", "Zebra", "Dolphin", "Monkey"]
chars = 0
for animal in animals:
    chars += len(animal)

print("Total characters: {}, Average length: {}".format(chars, chars/len(animals)))<jupyter_output><empty_output><jupyter_text>Week 4 - Iterating over Lists and Tuples - Exemplo<jupyter_code>winners = ["Ashley", "Dylan", "Reese"]
for index, person in enumerate(winners):
    print("{} - {}".format(index + 1, person))<jupyter_output><empty_output><jupyter_text>Week 4 - Iterating over Lists and Tuples - Desafio<jupyter_code>""" Week 4 - Iterating over Lists and Tuples - Desafio """
def skip_elements(elements):
	# code goes here
	new_elements = []
	for index, element in enumerate(elements):
		if index % 2 == 0:
			new_elements.append(element)		
	return new_elements

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']<jupyter_output><empty_output><jupyter_text>Week 4 - Iterating over Lists and Tuples - Exemplo<jupyter_code>def full_emails(people):
    result = []
    for email, name in people:
        result.append("{} <{}>".format(name, email))
    return result

print(full_emails([("<EMAIL>", "<NAME>"), ("<EMAIL>", "Shay Brandt")]))<jupyter_output><empty_output><jupyter_text>Week 4 - List Comprehensions - Exemplo<jupyter_code>"""Week 4 - List Comprehensions - Exemplo"""
multiples = []
for x in range(1, 11):
    multiples.append(x*7)
print(multiples)

# or use list comprehension

multiples = [7*x for x in range(1,11)]
print(multiples)<jupyter_output><empty_output><jupyter_text>Week 4 - List ComprehensionsLet us create new lists based on sequences or ranges  Week 4 - List Comprehensions - Exemplo<jupyter_code>languages = ["Python", "Pearl", "Ruby", "Go", "Java", "C"]
lengths = [len(language) for language in languages]
print(lengths)
#[6, 5, 4, 2, 4, 1]

z = [x for x in range(1, 101) if x % 3 == 0]
print(z)<jupyter_output><empty_output><jupyter_text>Week 4 - List Comprehensions - Desafio<jupyter_code>def odd_numbers(n):
	return [x for x in range(1, 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 []<jupyter_output><empty_output><jupyter_text>Lists and Tuples Operations Cheat SheetLists and tuples are both sequences, so they share a number of sequence operations. But, because lists are mutable, there are also a number of methods specific just to lists. This cheat sheet gives you a run down of the common operations first, and the list-specific operations second. Common sequence operationslen(sequence) Returns the length of the sequencefor element in sequence Iterates over each element in the sequenceif element in sequence Checks whether the element is part of the sequencesequence[i] Accesses the element at index i of the sequence, starting at zerosequence[i:j] Accesses a slice starting at index i, ending at index j-1. If i is omitted, it's 0 by default. If j is omitted, it's len(sequence) by default.for index, element in enumerate(sequence) Iterates over both the indexes and the elements in the sequence at the same time List-specific operations and methodslist[i] = x Replaces the element at index i with xlist.append(x) Inserts x at the end of the listlist.insert(i, x) Inserts x at index ilist.pop(i) Returns the element a index i, also removing it from the list. If i is omitted, the last element is returned and removed.list.remove(x) Removes the first occurrence of x in the listlist.sort() Sorts the items in the listlist.reverse() Reverses the order of items of the listlist.clear() Removes all the items of the listlist.copy() Creates a copy of the listlist.extend(other_list) Appends all the elements of other_list at the end of list List comprehension[expression for variable in sequence] Creates a new list based on the given sequence. Each element is the result of the given expression.[expression for variable in sequence if condition] Creates a new list based on the given sequence. Each element is the result of the given expression; elements only get added if the condition is true.    Quiz List: Week 4 1. 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.<jupyter_code>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 = []
for files in filenames:
    if files.endswith(".hpp"):
        newfilenames += [files[:-2]]
    else:
        newfilenames += [files]
print(newfilenames) 
# Should be ["program.c", "stdio.h", "sample.h", "a.out", "math.h", "hpp.out"]<jupyter_output><empty_output><jupyter_text>2. 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 ythonpay.<jupyter_code>def pig_latin(text):
  say = ""
  # Separate the text into words
  words = text.split()
  for word in words:
    # Create the pig latin word and add it to the list
    say += word[1:] + word[0] + "ay "
    # Turn the list back into a phrase
  return say
		
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"<jupyter_output><empty_output><jupyter_text>3. 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.<jupyter_code>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-------<jupyter_output><empty_output><jupyter_text>5. 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.<jupyter_code>def group_list(group, users):
  members = ", ".join(users)
  return "{}: {}".format(group, 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:"<jupyter_output><empty_output><jupyter_text>6. 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.<jupyter_code>def guest_list(guests):
	for guest in guests:
		name, age, profession = guest
		print("{0} is {1} years old and works as {2}".format(name, age, profession))

guest_list([('Ken', 30, "Chef"), ("Pat", 35, 'Lawyer'), ('Amanda', 25, "Engineer")])

#Click Run to submit code

#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<jupyter_output><empty_output><jupyter_text>Dictionaries  What is a dictionary?The data inside dictionaries take the form of pairs of keys and values<jupyter_code>""" What is a dictionary? - Exemplo """

file_counts = {"jpg":10, "txt":14, "csv":2, "py":23}
print(file_counts)

file_counts["txt"] #14
"jpg" in file_counts #True
"html" in file_counts #False

file_counts["cfg"] = 8
print(file_counts) #{'jpg': 10, 'txt': 14, 'csv': 2, 'py': 23, 'cfg': 8}

file_counts["csv"]  = 17
print(file_counts) #{'jpg': 10, 'txt': 14, 'csv': 17, 'py': 23, 'cfg': 8}

del file_counts["cfg"]
print(file_counts) #{'jpg': 10, 'txt': 14, 'csv': 17, 'py': 23}<jupyter_output><empty_output><jupyter_text>Questionar - What is a dictionary? 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.<jupyter_code>"""Questionar"""

toc = {"Introduction":1, "Chapter 1":4, "Chapter 2":11, "Chapter 3":25, "Chapter 4":30}
toc["Epilogue"] = 39 # Epilogue starts on page 39
toc["Chapter 3"] = 24 # Chapter 3 now starts on page 24
print(toc) # What are the current contents of the dictionary?
print("Chapter 5" in toc) # Is there a Chapter 5?<jupyter_output><empty_output><jupyter_text>Iterating over the Contents of a Dictionary - Exemplo<jupyter_code>file_counts = {"jpg": 10, "txt": 14, "csv": 2, "py": 23}
for extension in file_counts:
    print(extension)
#jpg txt csv py

for ext, amount in file_counts.items():
    print("There are {} files with the .{} extension".format(amount, ext))
#There are 10 files with the .jpg extension
#There are 14 files with the .txt extension
#There are 2 files with the .csv extension
#There are 23 files with the .py extension

file_counts.keys() #dict_keys(['jpg', 'txt', 'csv', 'py'])

file_counts.values() #dict_values([10, 14, 2, 23])

for value in file_counts.values():
    print(value) #10 14 2 23<jupyter_output><empty_output><jupyter_text>Iterating over the Contents of a Dictionary - QuestionarNow, it's your turn! Have a go at iterating over a dictionary! 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.<jupyter_code>cool_beasts = {"octopuses":"tentacles", "dolphins":"fins", "rhinos":"horns"}
for animal, caract in cool_beasts.items():
    print("{} have {}".format(animal, caract))<jupyter_output><empty_output><jupyter_text>Iterating over the Contents of a Dictionary - Exemplo<jupyter_code>def count_letters(text):
    result = {}
    for letter in text:
        if letter not in result:
            result[letter] = 0
        result[letter] += 1
    return result

print(count_letters("Hello word!!")) #{'H': 1, 'e': 1, 'l': 2, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1, '!': 2}<jupyter_output><empty_output><jupyter_text>Dictionaries vs. Lists - QuestionarIn 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.<jupyter_code>wardrobe = {"shirt":["red","blue","white"], "jeans":["blue","black"]}
for clothing, color in wardrobe.items():
	for color in color:
		print("{} {}".format(color, clothing))<jupyter_output><empty_output><jupyter_text>Dictionary Methods Cheat SheetDefinitionx = {key1:value1, key2:value2}  Operationslen(dictionary) - Returns the number of items in the dictionaryfor key in dictionary - Iterates over each key in the dictionaryfor key, value in dictionary.items() - Iterates over each key,value pair in the dictionaryif key in dictionary - Checks whether the key is in the dictionarydictionary[key] - Accesses the item with key key of the dictionarydictionary[key] = value - Sets the value associated with keydel dictionary[key] - Removes the item with key key from the dictionary Methodsdict.get(key, default) - Returns the element corresponding to key, or default if it's not presentdict.keys() - Returns a sequence containing the keys in the dictionarydict.values() - Returns a sequence containing the values in the dictionarydict.update(other_dictionary) - Updates the dictionary with the items coming from the other dictionary. Existing entries will be replaced; new entries will be added.dict.clear() - Removes all the items of the dictionary  Quiz Dictionaries 1. 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>).<jupyter_code>def email_list(domains):
	emails = []
	for address, users in domains.items():
	  for user in users:
	    emails.append("{}<EMAIL>(user, address))
	return(emails)

print(email_list({"gmail.com": ["clark.kent", "diana.prince", "peter.parker"], "yahoo.com": ["barbara.gordon", "jean.grey"], "hotmail.com": ["bruce.wayne"]}))<jupyter_output><empty_output><jupyter_text>2. 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.<jupyter_code>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 user in users:
			# Now add the group to the the list of
			# groups for this user, creating the entry
			# in the dictionary if necessary
			if user not in user_groups.keys(): 
				user_groups[user] = [group]
			else:
				user_groups[user].append(group)

	return(user_groups)

print(groups_per_user({"local": ["admin", "userA"],
		"public":  ["admin", "userB"],
		"administrator": ["admin"] }))<jupyter_output><empty_output><jupyter_text>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?<jupyter_code>wardrobe = {'shirt': ['red', 'blue', 'white'], 'jeans': ['blue', 'black']}
new_items = {'jeans': ['white'], 'scarf': ['yellow'], 'socks': ['black', 'brown']}
wardrobe.update(new_items)
print(wardrobe)<jupyter_output><empty_output><jupyter_text>5. The add_prices function returns the total price of all of the groceries in the  dictionary. Fill in the blanks to complete this function.<jupyter_code>def add_prices(basket):
	# Initialize the variable that will be used for the calculation
	total = 0
	# Iterate through the dictionary items
	for fruits, 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<jupyter_output><empty_output><jupyter_text>Module 4 Graded Assessment 1. The format_address function separates out parts of the address string into new strings: house_number and street_name, and returns: "house number X on street named Y". The format of the input string is: numeric house number, followed by the street name which may contain numbers, but never by themselves, and could be several words long. For example, "123 Main Street", "1001 1st Ave", or "55 North Center Drive". Fill in the gaps to complete this function.<jupyter_code>def format_address(address_string):
  # Declare variables
  address_list = []
  street_name = []
  # Separate the address string into parts
  address_list = address_string.split()
  # Traverse through the address parts
  for address in address_list:
    # Determine if the address part is the
    # house number or part of the street name
    if address.isnumeric():
      house_number = address
    else:
      street_name.append(address) 

  # Does anything else need to be done 
  # before returning the result?
  street_name = " ".join(street_name)
  # Return the formatted string  
  return "house number {} on street named {}".format(house_number, street_name)

print(format_address("123 Main Street"))
# Should print: "house number 123 on street named Main Street"

print(format_address("1001 1st Ave"))
# Should print: "house number 1001 on street named 1st Ave"

print(format_address("55 North Center Drive"))
# Should print "house number 55 on street named North Center Drive"<jupyter_output><empty_output><jupyter_text>2. The highlight_word function changes the given word in a sentence to its upper-case version. For example, highlight_word("Have a nice day", "nice") returns "Have a NICE day". Can you write this function in just one line?<jupyter_code>def highlight_word(sentence, word):
	return(sentence.replace(word, word.upper()))

print(highlight_word("Have a nice day", "nice"))
print(highlight_word("Shhh, don't be so loud!", "loud"))
print(highlight_word("Automating with Python is fun", "fun"))<jupyter_output><empty_output><jupyter_text>3. A professor with two assistants, Jamie and Drew, wants an attendance list of the students, in the order that they arrived in the classroom. Drew was the first one to note which students arrived, and then Jamie took over. After the class, they each entered their lists into the computer and emailed them to the professor, who needs to combine them into one, in the order of each student's arrival. Jamie emailed a follow-up, saying that her list is in reverse order. Complete the steps to combine them into one list as follows: the contents of Drew's list, followed by Jamie's list in reverse order, to get an accurate list of the students as they arrived.<jupyter_code>def combine_lists(list1, list2):
  # Generate a new list containing the elements of list2
  # Followed by the elements of list1 in reverse order
  list1.reverse()
  return list2 + list1

Jamies_list = ["Alice", "Cindy", "Bobby", "Jan", "Peter"]
Drews_list = ["Mike", "Carol", "Greg", "Marcia"]

print(combine_lists(Jamies_list, Drews_list))<jupyter_output><empty_output><jupyter_text>4. Use a list comprehension to create a list of squared numbers (n*n). The function receives the variables start and end, and returns a list of squares of consecutive numbers between start and end inclusively.For example, squares(2, 3) should return [4, 9].<jupyter_code>def squares(start, end):
	return [ square*square for square in range(start, end+1) ]

print(squares(2, 3)) # Should be [4, 9]
print(squares(1, 5)) # Should be [1, 4, 9, 16, 25]
print(squares(0, 10)) # Should be [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]<jupyter_output><empty_output><jupyter_text>5. Complete the code to iterate through the keys and values of the car_prices dictionary, printing out some information about each one.<jupyter_code>def car_listing(car_prices):
  result = ""
  for car, price in car_prices.items():
    result += "{} costs {} dollars".format(car, price) + "\n"
  return result

print(car_listing({"<NAME>":19000, "<NAME>":55000, "Ford Fiesta":13000, "Toyota Prius":24000}))<jupyter_output><empty_output><jupyter_text>6. Taylor and Rory are hosting a party. They sent out invitations, and each one collected responses into dictionaries, with names of their friends and how many guests each friend is bringing. Each dictionary is a partial list, but Rory's list has more current information about the number of guests. Fill in the blanks to combine both dictionaries into one, with each friend listed only once, and the number of guests from Rory's dictionary taking precedence, if a name is included in both dictionaries. Then print the resulting dictionary.<jupyter_code>def combine_guests(guests1, guests2):
  # Combine both dictionaries into one, with each key listed 
  # only once, and the value from guests1 taking precedence
  list_guests = {}

  list_guests.update(guests2)
  list_guests.update(guests1)

  return list_guests
  

Rorys_guests = { "Adam":2, "Brenda":3, "David":1, "Jose":3, "Charlotte":2, "Terry":1, "Robert":4}
Taylors_guests = { "David":4, "Nancy":1, "Robert":2, "Adam":1, "Samantha":3, "Chris":5}

print(combine_guests(Rorys_guests, Taylors_guests))<jupyter_output><empty_output><jupyter_text>7. Use a dictionary to count the frequency of letters in the input string. Only letters should be counted, not blank spaces, numbers, or punctuation. Upper case should be considered the same as lower case. For example, count_letters("This is a sentence.") should return {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}.<jupyter_code>def count_letters(text):
  result = {}
  # Go through each letter in the text
  for letter in text.lower():
    # Check if the letter needs to be counted or not
    if letter.isalpha():
    # Add or increment the value in the dictionary
      if letter not in result:
        result[letter] = 0
      result[letter] += 1
  return result

print(count_letters("AaBbCc"))
# Should be {'a': 2, 'b': 2, 'c': 2}

print(count_letters("Math is fun! 2+2=4"))
# Should be {'m': 1, 'a': 1, 't': 1, 'h': 1, 'i': 1, 's': 1, 'f': 1, 'u': 1, 'n': 1}

print(count_letters("This is a sentence."))
# Should be {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}<jupyter_output><empty_output><jupyter_text>8. What do the following commands return when animal = "Hippopotamus"?<jupyter_code>print(animal[3:6])
print(animal[-5])
print(animal[10:])<jupyter_output><empty_output><jupyter_text>9. What does the list "colors" contain after these commands are executed?<jupyter_code>colors = ["red", "white", "blue"]
colors.insert(2, "yellow")<jupyter_output><empty_output><jupyter_text>10. What do the following commands return?<jupyter_code>host_addresses = {"router": "192.168.1.1", "localhost": "127.0.0.1", "google": "8.8.8.8"}
host_addresses.keys()

#{"router": "192.168.1.1", "localhost": "127.0.0.1", "google": "8.8.8.8"}
#["router", "192.168.1.1", "localhost", "127.0.0.1", "google", "8.8.8.8"]
#['192.168.1.1', '127.0.0.1', '8.8.8.8']
#['router', 'localhost', 'google']<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12465625417167267, 'fraction_numerical': 0.020184221065278334, 'mean_word_length': 5.001602307322544, 'pattern_counts': {'":': 56, '<': 201, '<?xml version=': 0, '>': 204, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 12, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '46', 'dir': 'jupyter-structured-clean-dedup', 'id': '223932', 'license': 'MIT', 'n_tokens_mistral': 12659, 'n_tokens_neox': 11785, 'n_words': 4462, 'path': 'Crash Course on Python/.ipynb_checkpoints/Week_4-checkpoint.ipynb', 'repo_name': 'guhls/python-courses', 'size': '37531'}