Python Part 2: Programming

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

Review 12) Multiple Returns Define a function calculate_range that consumes a temperature and returns a tuple of two numbers, the high and the low. These numbers are calculated as follows: high = temperature + 20 low = temperature - 30 Then, you will need to call your function once to create two variables today_low and today_high for today's temperature of 70. Note: You are not allowed to use list or tuple indexing.

def calculate_range(temperature): high = temperature + 20 low = temperature - 30 temp_tuple=(high,low) return temp_tuple today_high, today_low = calculate_range(70) print(today_high) print(today_low)

Review 2) String Cleaning Define a function clean_string that consumes a string and returns a new, cleaned string. To clean a string, you will need to: Strip whitespace from the end Replace any plus signs with spaces So, for example, the string " Hello+World " would become "Hello World".

def clean_string(string): return string.replace("+"," ").strip(" ") print(clean_string(" Hello+World "))

Review 13) Function in File Define a function convert_emphasis that consumes a single character string and returns 1 if it is a "!", 2 if it is a "?", or 0 otherwise. Then apply this function to each character in the given file, and calculate the sum. Preview rambling.txt: What!!?? What are you talking about!!?? Why would you say that!? I can hardly believe this. What a joke!!!! Do you even know what you're talking about???? I didn't think so!

def convert_emphasis(character): if character=="!": return 1 elif character=="?": return 2 else: return 0 rambling_path ="rambling.txt" rambling_file = open(rambling_path,'r') sum_text=0 for line in rambling_file: for character in line: sum_text=sum_text+convert_emphasis(character) print(sum_text) rambling_file.close()

Review 6) Without Meat Define a function filter_toppings that consumes a list of strings and returns a new list. This new list should not have any of the following strings, regardless of capitalization: "ham", "bacon", "sausage". For example, the list ["Bacon", "Onions", "green pepper", "HAM"] would return ["Onions", "green pepper"].

def filter_toppings(a_list): new_list=[] for item in a_list: if item.lower() !="ham" and item.lower() !="bacon" and item.lower() !="sausage": new_list.append(item) return new_list print(filter_toppings(["Bacon", "Onions", "green pepper", "HAM"]))

Review 4) Is Sentence? Define a function is_sentence that consumes a string and returns a boolean indicating whether the string ends in a ".", "?", or "!". For example, the string "Hello?" would return True but the string "Dog" would return False. Note: You are not allowed to use an if statement.

def is_sentence(string): return string[-1]=="." or string[-1]=="!" or string[-1]=="?" <---one line print(is_sentence("Dog"))

Review 3) More Demanding Define a function make_demanding that consumes a string and returns a new, more demanding string. To make a string more demanding, add the string ", now!" to the end. For example, the string "Pass the butter" would become "Pass the butter, now!".

def make_demanding(string): change_string = string + ", now!" return change_string print(make_demanding("Pass the butter")) or def make_demanding(string): return string + ", now!" print(make_demanding("Pass the butter"))

Review 14) File Sum Define a function sum_file that consumes a string representing a filename and returns a number. This number will represent the sum of all the numbers in the given file. Assume that all files will have each number on their own line. simple.txt Preview: 1 1 1 bigger.txt Preview: 100 100 100 200 200 300 400 500

def sum_file(file_name): a_file=open(file_name) file_sum = 0 for line in a_file: amount = int(line) file_sum = file_sum + amount a_file.close() return file_sum print(sum_file('simple.txt')) print(sum_file('bigger.txt'))

Review 8) Get Data Define a function get_data that consumes a dictionary and returns the value associated with the key "Data". If the key "Data" is not in the dictionary, then return the value 0 instead.

dict={'not':1} def get_data(dict): if 'Data' in dict: return dict['Data'] else: return 0 print(get_data(dict)) OR dict={'not':1} def get_data(dict): return dict.get('Data', 0) print(get_data(dict))

Review 5) Convert Each Define a function convert_distance that consumes a number (representing distance in kilometers) and returns that number converted to meters by applying the following formula: meters = kilometers * 1000 Then use this function to convert each element of the given list and print the result.

distances = [10, 5, 4.3] def calculate_distance(distance): return distance *1000 for distance in distances: print(calculate_distance(distance))

Review 15) Builtin string The string module contains a variable named punctuation (a string of characters like ".*&^"). Import and use this variable to print a Boolean value indicating whether the user-inputted string (from input) is a punctuation symbol. If the user types more than one character, you can print out False. Note: You are not allowed to use an if statement.

from string import punctuation command="" command=input("Enter one character:") print(command in punctuation and len(command)==1)

Review 16) Process JSON The given file contains JSON data. Use the data associated with the "Employees" key (a list inside of a dictionary inside of a dictionary inside of a dictionary) to plot the distribution of employees. report.json Preview: {"Title": "Business Report", "Generated": "11/20/2017 at 1:09pm", "Authors": ["Ada Lovelace", "Alan Turing", "Guido von Rossum"], "Records": { "Number of Records": 4, "Span": [ "8-11-2017", "12-20-2017" ], "Data": { "Sales": [46, 50, 47, 56, 54, 45, 55, 37, 54, 46, 64, 55, 56, 55, 52, 53, 39, 68, 55, 55, 44, 39, 62, 56, 53, 42, 35, 43, 42, 51], "Revenue": [66, 52, 53, 42, 49, 57, 55, 49, 54, 55, 51, 50, 57, 50, 46, 64, 43, 64, 45, 52, 30, 55, 38, 64, 40, 49, 59, 38, 63, 54], "Employees": [11, 8, 10, 3, 11, 14, 6, 17, 7, 7, 6, 14, 9, 8, 10, 6, 9, 7, 12, 8, 11, 18, 14, 9, 11, 11, 14, 8, 11, 4], "Dogs": [20, 19, 16, 19, 19, 15, 16, 16, 21, 23, 24, 14, 19, 16, 21, 14, 23, 17, 24, 25, 21, 17, 16, 17, 20, 19, 15, 21, 19, 22] } } }

import json json_file = open('report.json') data = json.load(json_file) employee_data=data['Records']['Data']["Employees"] import matplotlib.pyplot as plt plt.hist(employee_data) plt.show() json_file.close()

Review 7) Sum User Input Use the input function to consume a plus-separated string of numbers from the user (e.g., 4+2+3). Add up all these numbers and print their sum (9, in the case shown before).

inputs=input('Enter a srting of numbers you want to add.') numbers = inputs.split('+') total=0 for number in numbers: total=total+int(number) print(total)

Print out each of the following literal values on their own lines: A non-empty string (str)

print("hello")

Print out each of the following literal values on their own lines: A tuple of two strings (tuple)

print(('python', 'geeks')) *Remember the parenthesis

Print out each of the following literal values on their own lines: A negative float (float)

print(-5.0)

Print out each of the following literal values on their own lines: A positive integer (int)

print(5)

Print out each of the following literal values on their own lines: A boolean (bool)

print(5==5) result: True

Print out each of the following literal values on their own lines: A None (None)

print(None)

Print out each of the following literal values on their own lines: A non-empty list of integers (list)

print([1,2,4,4])

Review 9) Extract Cast The following complex, nested data structure represents movies. Use a combination of list indexing and dictionary access to print out the third character in the second movie. movies = [ {"Name": "Iron Man", "Length": 126, "Characters": ["Tony", "Pepper", "Obidiah"]}, {"Name": "Thor", "Length": 130, "Characters": ["Thor", "Jane", "Loki"]}, {"Name": "Captain America", "Length": 126, "Characters": ["Steve", "Peggy", "Bucky"]}]

print(movies[1]["Characters"][2])

Print out each of the following literal values on their own lines: A non-empty dictionary mapping strings to integers (dict)

print({"first":1, "second":2,'third':3})

Review 10) Complex Addition The following complex, nested data structure represents books. Print out the total price of all the books summed together. books = [ {"Title": "Great Expectations", "Pages": 321, "Sales": {"Price": 10, "In Stock?": "True"}}, {"Title": "The Grapes of Wrath", "Pages": 470, "Sales": {"Price": 5, "In Stock?": "True"}}, {"Title": "Pride & Prejudice", "Pages": 273, "Sales": {"Price": 20, "In Stock?": "True"}}, ] Note: You cannot simply print out a literal value. You must use the books variable, dictionary access, and a looping pattern to calculate the sum for any list of books structured like this. The valid looping patterns are for loops and list comprehensions.

total_price=0 for title in books: total_price=total_price+title['Sales']['Price'] print(total_price)

Review 11) Double Count The following complex, nested data structure represents multiple students' scores over multiple assignments. Count the total number of scores. books = [ {"Title": "Great Expectations", "Pages": 321, "Sales": {"Price": 10, "In Stock?": "True"}}, {"Title": "The Grapes of Wrath", "Pages": 470, "Sales": {"Price": 5, "In Stock?": "True"}}, {"Title": "Pride & Prejudice", "Pages": 273, "Sales": {"Price": 20, "In Stock?": "True"}}, ] Note: You are not allowed to use list indexing.

total_price=0 for title in books: total_price=total_price+title['Sales']['Price'] print(total_price)


Kaugnay na mga set ng pag-aaral

everfi module 1-6 (business finance)

View Set

Health Assessment- PrepU Chapter 16 Assessing Eyes

View Set

NUR108 #2 & 3 - Chapter 36: Nursing Care of the Child with an Alteration in Comfort-pain Assessment and Management

View Set