Python In-Labs and HWs for Final

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

Consider the following Python code: state = 'North Carolina' sl = len(state) choice = int(raw_input('Enter a number between 0 and ' + str(sl - 1) + ': ')) if 0 <= choice < sl: print state[choice] else: print 'Invalid entry!' For each of the user inputs below, select the correct output from this code 0: 12: 14: 4:

0: N 12: n 14: Invalid Entry! 4: h

Given a user input of 7, what is the output of the following Python code? t = 0 v = int(raw_input('Enter a number: ')) for n in range(v): t += n print t

21

True or False: In Python, all of the elements of a list must be the same type.

False

True or False: In a Python dictionary, the order of items is always the order that the key-value pairs are added to the dictionary.

False

True or False: Like a list, the elements of a tuple can be modified.

False

True or False: Numpy array elements cannot be accessed using an index in the same way they are used for lists and tuples.

False

True or false: A single try: statement can have only one except: statement.

False

What type of error will be raised if you try to access a key that is not in the dictionary?

KeyError

Given the following code, select the correct output: temp_str = "Second argument: {1}, first one: {0}" arg1 = 47 arg2 = 11 out_str = temp_str.format(arg1, arg2) print out_str

Second argument: 11, first one: 47

True or False: In a Python dictionary, a key is used to access a value stored in the dictionary.

True

True or False: When you are finished reading from or writing to a file, your program should close the file.

True

True or False: A numpy array can be created from a list as long as the values are all of the same type.

True

True or false: In Python, an exception indicates that something unusual has occurred during a program's execution that may cause the program to be in an unstable state.

True

Consider the Python code below and answer the following questions def fun(lst1, lst2, str1): if len(lst1) > 3: lst1 = lst1[:3] lst2[0] = 'ahoy' str1 = ''.join(lst2) arg1_lst = ['a','b','c','d'] arg2_lst = ['hello', 'mother', 'and', 'father'] arg_str = 'sister' fun(arg1_lst, arg2_lst, arg_str) print arg1_lst # Print 1 What is the output generated by the print statement at the line marked Print 1?

['a', 'b', 'c', 'd']

Consider the Python code below and answer the following questions def fun(lst1, lst2, str1): if len(lst1) > 3: lst1 = lst1[:3] lst2[0] = 'ahoy' str1 = ''.join(lst2) arg1_lst = ['a','b','c','d'] arg2_lst = ['hello', 'mother', 'and', 'father'] arg_str = 'sister' fun(arg1_lst, arg2_lst, arg_str) print arg2_lst # Print 2 What is the output generated by the print statement at the line marked Print 2?

['ahoy', 'mother', 'and', 'father']

Which of the following is not a valid list definition in Python? ['crunchy frog', 'ram bladder', 'lark vomit'] ['Cheddar', 'Edam', 'Gouda'] [] ['spam', 2.0, 5, [10, 20] [10, 20, 30, 40]

['spam', 2.0, 5, [10, 20]

Consider the following function definition: def fun(t, e, i): ret = t[:i] ret.append(e) return ret + t[i:] What is the output from the following code? lst = [1,2,3,4,5] print fun(lst, 'spam', 2)

[1, 2, 'spam', 3, 4, 5]

Select all of the correct ways to create a dictionary object in Python. (a) sp2ger = {'uno'='ein', 'dos'='zwei', 'tres'='drei'} (b) sp2ger = () (c) sp2ger = {} (d) sp2ger = dict() (e) sp2ger = {'uno': 'ein', 'dos': 'zwei', 'tres': 'drei'} (f) sp2ger = ['uno': 'ein', 'dos': 'zwei', 'tres': 'drei']

c, d, e

Define a function char_hist that takes in a dictionary and a string. The dictionary will be used to keep track of the number of times each character occurred in the string. Your function will not return, it will modify the given dictionary instead.

def char_hist(histogram,string): for character in string: histogram[character] = histogram.get(character,0)+1

Define a function concatenate_arrays( arr1, arr2 ) that takes in two arrays and returns an array containing the contents of arr1 and arr2.

def concatenate_arrays(arr1,arr2): arr1 = np.array(arr1) arr2 = np.array(arr2) arr = np.concatenate((arr1,arr2)) return arr

Define a function convert_to_coins that takes in a integer representing some dollar amount in cents (so 1267 would be passed in for $12.67). Your function will return a tuple with the lowest number of quarters (25 cents), dimes (10 cents), nickels (5 cents), and pennies (1 cent) necessary to represent that amount.

def convert_to_coins(integer): quarter = int(integer/25) remainder = integer % 25 dime = int(remainder/10) remainder1 = remainder % 10 nickel = int(remainder1/5) penny = remainder1 % 5 total = quarter, dime, nickel, penny return total

Define a function format_correctly( string ) that takes in a string as an argument. It will return a correctly-formatted version of the given string that 1) stripped the given string of any surrounding whitespace 2) made the first character of the string capitalized 3) made the remaining characters in the string lowercase. You can assume the given string will consist of all letters.

def format_correctly(string): string = string.strip() s1 = string[0] s1 = s1.upper() s2 = string[1:] s2 = s2.lower() string = s1 + s2 return string

Define a function generate_kv_strings that takes in a dictionary as the argument. Your function will iterate through the dictionary to create then return a list of strings representing each key-value pair from the dictionary, where each string will be in the format "key: value" (where key and value are the respective keys and values from the given dictionary).

def generate_kv_strings(dictionary): lists = [] for key,value in dictionary.items(): strings = key + ':' + value lists.append(strings) return lists

Define a function list_max that takes in a list of numbers as an argument. Your function will iterate through the list with a for loop and return the largest value in the given list. Your function only has to work on numerical values. Do not use the built-in max or min function or the .sort() method.

def list_max(lists): maxv = lists[0] for number in lists: if number > maxv: maxv = number return maxv

Define a function list_min that takes in a list of numbers as an argument. Your function will iterate through the list with a for loop and return the smallest value in the given list. Your function only has to work on numerical values.

def list_min(lists): minv = lists[0] for number in lists: if number < minv: minv = number return minv

Define a function manhattan_distance that takes in two tuples representing (x,y) coordinates. Your function will return the manhattan distance (defined below) between the two provided coordinates.

def manhattan_distance((x1,y1),(x2,y2)): x_distance = abs(x2-x1) y_distance = abs(y2-y1) distance = x_distance + y_distance return distance

Define a function matrix_multiplication( matrix1, matrix2 ) that takes in two 2D arrays of integers and returns the product. A matrix multiplication example has been provided below.

def matrix_multiplication(matrix1, matrix2): a = np.matrix(matrix1) b = np.matrix(matrix2) return a*b

Define a function reverse_lookup that takes in a dictionary and a value. Your function will find and return a key associated with with the inputted value if one exists. If the value is not in the dictionary, return None.

def reverse_lookup(dictionary, value): for k,v in dictionary.items(): if v == value: return k

Define a function space_to_underscore that takes in a string as an argument. Your function will return a copy of that string containing underscores ( _ ) in place of spaces.

def space_to_underscore(string): string = string.replace(' ','_') return string

Define a function sum_lists that takes in a list of lists, which contain all numerical values. Your function will return the sum of all the elements in the sublists. You may use the built-in sum function.

def sum_lists(lists): total = 0 for value in lists: for number in value: total += number return total

Define a function to_string that takes in a list. Your function will iterate through the list to generate and return the concatenation of the items in the list.

def to_string(lists): string = "" for var in lists: string += var return string

Define a function add_word_count_to_file that takes in a filename (a string) as the argument. Your function will open a file object for the given filename, count the number of words in the file, and add a line "There are [word count] words in the above text." to the end of the file, where [word count] would be replaced with the actual number of words in the file. Your function should not return anything.

import csv def add_word_count_to_file(filename): count = 0 with open(filename,'r+') as f_in: for word in f_in: count += len(word.split()) with open(filename, 'a') as f_out: line = "\n There are " + str(count) + " words in the above text." f_out.write(line)

Define a function calculate_class_averages that takes in a csv filename (a string). Your function will read through each row of data, calculate the class average for each test, and return a tuple containing three floats: (test_1_average, test_2_average, test_3_average).

import csv def calculate_class_averages(string): with open(string) as f_in: f_in.readline() reader = csv.reader(f_in) lt1= [] lt2= [] lt3= [] for name,t1,t2,t3 in reader: t1=int(t1) lt1.append(t1) t2=int(t2) lt2.append(t2) t3=int(t3) lt3.append(t3) t1avg = sum(lt1)/float(len(lt1)) t2avg = sum(lt2)/float(len(lt2)) t3avg = sum(lt3)/float(len(lt3)) return (t1avg,t2avg,t3avg)

Define a function calculate_test_averages that takes in a csv filename (a string). Your function will read through each row of data and return a list of tuples, each formatted as (name, average), where average is the sum of the three listed test scores for the student. You can assume the tests are all weighted the same.

import csv def calculate_test_averages(filen): list1 = [] with open(filen) as f_in: f_in.readline() reader = csv.reader(f_in) for name,t1,t2,t3 in reader: avg = (float(t1)+float(t2)+float(t3))/3.0 list1.append((name,avg)) return list1

Define a function copy_every_other_line that takes an input filename (a string) and an output filename (a string). The input filename should be the name of a file that exists. The output filename is the name of a file that you will create and write to (or if it already exists, you'll overwrite it). Your function will do the following: open a file object for each of them, read through the input file object, and write every other line from the input file object into the output file object. Your function should not return anything.

import csv def copy_every_other_line(inputs,outputs): inputs = open(inputs, 'r') outputs = open(outputs,'w') count = False for line in inputs: count = not count if count: outputs.write(line) inputs.close() outputs.close()

Define a function get_int_choice that takes in a prompt (a string). Your function will display the given prompt, wait for the user to enter a value, convert it to an integer, and return the integer. If the user enters a non-integer value, the ValueError should be handled by a try/except block, the message "You did not enter an integer value. Please try again." should be displayed to the user, and the function should loop back to the beginning.

import csv def get_int_choice(prompt): T = True while T: string = raw_input(prompt) try: return int(string) except ValueError: print "You did not enter an integer value. Please try again."

Define a function write_with_averages that takes in an input csv filename (a string) and an output csv filename (a string), where the input csv filename is the name of a file that exists and the output csv filename is the name of the file you will write your output to. Your function should create a copy of the input csv file with an extra column containing each student's test average. Your function should not return anything.

import csv def write_with_averages(inputs, outputs): with open(inputs,'r') as inputs: inputs.readline() reader = csv.reader(inputs) lists=[] for name,T1,T2,T3 in reader: total = float(T1)+float(T2)+float(T3) average = total/3 lists.append([name,T1,T2,T3,average]) with open(outputs,'w') as outputs: header = ['Name','Test1','Test2','Test3','Average'] writer = csv.writer(outputs) writer.writerow(header) for name, T1, T2, T3, average in lists: writer.writerow([name,T1,T2,T3,average])

The commonly accepted way to import the numpy module is

import numpy as np

Define a function mean_median_for_test that takes in a csv filename (a string) and a test number (an integer). Your function will load in all of the grades for that test and return the mean and median for that test. Your implementation must use numpy.loadtxt.

import numpy as np def mean_median_for_test(fin, test_num): data = np.loadtxt(fin, usecols=[test_num], delimiter=',', skiprows=1) median = np.median(data) mean = np.mean(data) return mean, median

Define a function min_max_for_test that takes in a csv filename (a string) and a test number (an integer). Your function will load in all of the grades for that test and return the minimum grade and maximum grade for that test. Your implementation must use numpy.loadtxt.

import numpy as np def min_max_for_test(fin, test_num): data = np.loadtxt(fin, usecols=[test_num], delimiter=',', skiprows=1) minimum = np.amin(data) maximum = np.amax(data) return minimum, maximum

Define a function calculate_areas that takes in an array of radii (an array of numbers) and returns an array containing the areas of circles with the given radii.

import numpy as np import math def calculate_areas(radii): radii = np.array(radii) area = math.pi*radii**2 return area

Define a function check_extension that takes in a filename (a string) and an extension (a string). Your function should return True if the filename ends with the given extension and return False otherwise.

import numpy as np import matplotlib.pyplot as plt def check_extension(fname, ext): output = fname.endswith(ext) return output

Define a function called plot_averages that takes in a filename (a string). We will be using the a csv file with seven columns representing student test grades and their time spent studying (in minutes): Name, Test1, Test2, Test2, Time1, Time2, Time3 Your function will load the grades and study times for each test. It will find the average grade for each of the the three tests and the average time spent studying for each of the three tests. It will plot the averaged study times (there should be 3 averages, one for each test) on the x-axis and the averaged grades (there should be 3 averages, one for each test) on the y-axis. Plot your points with red circles.

import numpy as np import matplotlib.pyplot as plt def plot_averages(fname): grades1 = np.loadtxt(fname, usecols=[1], delimiter=',', skiprows=1) grades2 = np.loadtxt(fname, usecols=[2], delimiter=',', skiprows=1) grades3 = np.loadtxt(fname, usecols=[3], delimiter=',', skiprows=1) time1 = np.loadtxt(fname, usecols=[4], delimiter=',', skiprows=1) time2 = np.loadtxt(fname, usecols=[5], delimiter=',', skiprows=1) time3 = np.loadtxt(fname, usecols=[6], delimiter=',', skiprows=1) test1_mean = np.mean(grades1) test2_mean = np.mean(grades2) test3_mean = np.mean(grades3) time1_mean = np.mean(time1) time2_mean = np.mean(time2) time3_mean = np.mean(time3) plt.plot([time1_mean],[test1_mean],'ro') plt.plot([time2_mean],[test2_mean],'ro') plt.plot([time3_mean],[test3_mean],'ro') plt.show()

Define a function scatter_plot_for_test that takes in a filename (a string) and an integer representing a test number. We will be using a csv file with seven columns representing student test grades and their time spent studying (in minutes): Name,Test1,Test2,Test3,Time1,Time2,Time3

import numpy as np import matplotlib.pyplot as plt def scatter_plot_for_test(fname,integer): grades = np.loadtxt(fname,usecols=[int(integer)],delimiter=',', skiprows=1) study = np.loadtxt(fname,usecols=[int(integer)+3],delimiter=',',skiprows=1) plt.plot([study],[grades],'bo') plt.show()

What is the output of the following Python code? my_str = 'Mississippi' res = '' idx = 0 while (idx < len(my_str)): c = my_str[idx] res = c + res idx += 1 print res

ippississiM

When used to read the contents of a structured text file, the loadtxt function in the numpy module returns a(n)

numpy.ndarray

What is the output from the following Python code? fruit = 'tomato' letter = fruit[1] print letter

o

Choose the selection that best completes this sentence: When the csv.reader function is called with a file object, the reader returns an object that allows you to...

read one line at a time from the file

Consider the following Python code: s = 'Monty Python' s1 = s[0:5] s2 = s[6:12] s3 = s[:4] s4 = s[7:] For each of the variables listed below, select the value that is stored in that variable. s4: s3: s1: s2:

s4: ython s3: Mont s1: Monty s2: Python

Consider the Python code below and answer the following 3 questions def fun(lst1, lst2, str1): if len(lst1) > 3: lst1 = lst1[:3] lst2[0] = 'ahoy' str1 = ''.join(lst2) arg1_lst = ['a','b','c','d'] arg2_lst = ['hello', 'mother', 'and', 'father'] arg_str = 'sister' fun(arg1_lst, arg2_lst, arg_str) print arg_str # Print 3 What is the output generated by the print statement at the line marked Print 3?

sister

Given: number_str = raw_input('Input a floating-point number: ') invalid = True while invalid: # Line 1 print 'The number is ', number_float We want code that will continue to prompt the user for input until a correctly formatted floating-point value is entered so it can be printed at the bottom. Which of the following is the correct replacement for the comment at Line 1? Select one:

try: number_float = float(number_str) invalid = False except ValueError: number_str = raw_input('Try again: Input a floating-point number: ')

Consider the following Python code: x = "spam" y = 45.201 x, y = y, x Select the choices that indicate the correct values stored in the variables x and y.

x has the value 45.201 y has the value 'spam'


Conjuntos de estudio relacionados

Erik Erikson's Psychosocial Theory of Development

View Set

Industrial Internet of Things IIoT

View Set

Chinese Religious Traditions (Midterm)

View Set

UNIT 5 psych 101 bsu final review

View Set