ch 7 - 9 algorithm

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

Write an expression that returns True if string s ends with "ism".

s.endswith('ism')

What does the get method do if the specified key is not found in the dictionary?

It returns a default value.

Write a statement that associates t with the empty tuple.

t = ()

A dictionary can include the same value several times but cannot include the same key several times.

true

Remove the smallest element from the set, s. Assume the set is not empty.

min = None for e in s : if min == None or e < min : min = e s.remove(min)

Given: a variable named incompletes that refers to a list of student ids, and a variable student_id that has already been assigned a value Write some code that counts the number of times the value associated with student_id appears in the list associated with incompletes and assigns this value to number_of_incompletes. You may use, if you wish, an additional variable, k. You may use only k, incompletes, student_id, and number_of_incompletes.

number_of_incompletes = 0 for k in incompletes: if student_id == k: number_of_incompletes += 1

Write an expression that evaluates to True if string s starts with "p".

s.startswith("p")

Given that d refers to a dictionary, change the value mapped to by the key 'Monty' to 'Python'.

d['Monty'] = 'Python'

Given that k refers to a non-negative int and that alist has been defined to be a list with at least k+1 elements, write a statement that removes the element at index k.

del alist[k]

Sets are created using curly braces { }.

false

Sets are immutable.

false

The elements in a dictionary are stored in ascending order, by the keys of the key-value pairs.

false

In a dictionary, you use a(n) ________ to locate a specific value.

key

Which method would you use to get all the elements in a dictionary returned as a list of tuples?

keys

Which would you use to get the number of elements in a dictionary?

len

Given a variable, us_cabinet, that is associated with a dictionary that maps department names to department heads, replace the value "Gonzalez" with "Mukasey" for the key "Justice Department".

us_cabinet["Justice Department"] = "Mukasey"

Given that a refers to a list, write the necessary code to reverse the elements of the list.

a.reverse()

Write a statement that associates d with a one-entry dictionary that maps the str 'answer' to the int value 42.

d = {'answer': 42}

Write an expression whose value is the concatenation of the three strigs name1, name2, and name3, separated by commas. So if name1, name2, and name3, were (respectively) "Neville", "Dean", and "Seamus", your expression's value would be "Neville,Dean,Seamus".

name1+ ','+ name2 +','+ name3

Given that s refers to a set, write a statement that attempts to remove integer 11 from the set, but will do nothing if 11 is not in the set.

s.discard(11)

Write an expression whose value is True if all the letters in string s are all lowercase.

s.islower()

Write an expression whose value is True if all the letters in string s are uppercase.

s.isupper()

Write an expression that is the concatenation of the strings "Hello" and "World".

'Hello'+'World'

ssume there is a variable, album_artists, that is associated with a dictionary that maps albums to performing artists. Write a statement that inserts the key/value pair: "Live It Out"/"Metric".

album_artists["Live It Out"]="Metric"

Given that d refers to a dictionary, write an expression that is the value to which the dictionary maps the key 'answer'.

d['answer']

Write the definition of a function named sum_list that has one parameter, a list whose elements are of type int. The function returns the sum of the elements of the list as an int.

def sum_list(list): sum = 0 for i in list: sum += i return sum

Assume the variable big references a string. Write a statement that converts the string it references to lowercase and assigns the converted string to the variable little.

little = big.lower()

A list named parking_tickets has been defined to be the number of parking tickets given out by the city police each day since the beginning of the current year. (Thus, the first element of the list contains the number of tickets given on January 1; the last element contains the number of tickets given today.)Write some code that associates most_tickets with the largest value found in parking_tickets. You may, if you wish, use one additional variable, k.

most_tickets = parking_tickets[0] for k in parking_tickets: if k > most_tickets: most_tickets = k

Assume the following statement appears in a program:days = 'Monday Tuesday Wednesday' Write a statement that splits the string, creating the following list named my_list:['Monday', 'Tuesday', 'Wednesday']

my_list = days.split()

Assume my_tuple references a tuple. Write a statement that converts it to a list named my_list.

my_list = list(my_tuple)

Assume the following statement appears in a program:values = 'one$two$three$four' Write a statement that splits the string, creating the following list named my_list:['one', 'two', 'three', 'four']

my_list = values.split('$')

Assume my_list references a list. Write a statement that converts it to a tuple named my_tuple.

my_tuple = tuple(my_list)

Write a statement that creates a two-dimensional list names mylist with three rows and four columns. Each element should be assigned the value 0.

mylist = [[0,0,0,0],[0,0,0,0],[0,0,0,0]]

Given three dictionaries, associated with the variables, canadian_capitals, mexican_capitals, and us_capitals, that map provinces or states to their respective capitals, create a new dictionary that combines these three dictionaries, and associate it with a variable, nafta_capitals.

nafta_capitals = {} for key in us_capitals : nafta_capitals[key] = us_capitals[key] for key in canadian_capitals : nafta_capitals[key] = canadian_capitals[key] for key in mexican_capitals : nafta_capitals[key] = mexican_capitals[key]

Assume that name is a variable of type string that has been assigned a value. Write an expression whose value is a string containing the first character of the value of name. So if the value of name were "Smith" the expression's value would be "S".

name[0:1]

Given the lists, lst1 and lst2, create a new sorted list consisting of all the elements of lst1 that also appears in lst2. For example, if lst1 is [4, 3, 2, 6, 2] and lst2 is [1, 2, 4], then the new list would be [2, 2, 4]. Note that duplicate elements in lst1 that appear in lst2 are also duplicated in the new list. Associate the new list with the variable new_list, and don't forget to sort the new list.

new_list = [] for i in lst1 : if i in lst2 : new_list.append(i) new_list.sort()

Write a statement that associates s with the empty set.

s = set()

Assume the variable s has been assigned a value, and the variable the_set refers to a set. Write an expression that whose value is True if the value that is referenced by s is in the_set.

s in the_set

Given that s refers to a set, write a statement that adds integer 42 to the set.

s.add(42)

Given that s refers to a set, write a statement that removes integer 5 from the set.

s.remove(5)

Write an expression that is the concatenation of two strings s1 and s2.

s1 + s2

Write an expression whose value is the last character in string s.

s[-1] s[6]

Write an expression whose value is the string that consists of the first four characters of string s.

s[0:4]

Write an expression whose value is the string that consists of the second through fifth characters of string s.

s[1:5]

Write an expression whose value is the character at index 3 of string s.

s[3]

Write an expression whose value is the string consisting of all the characters (starting with the sixth) of string s.

s[5:]

Write a program with a function that accepts a string as an argument and returns a copy of the string with the first character of each sentence capitalized. The program should let the user enter a string and then pass it to the function, printing out the modified string.

sentence = input("Enter sentence to be capitalized:") def capitalize(sentence): for i in range(0, len(sentence)): if i == 0: sentence = sentence[i].upper() + sentence[1:] elif sentence[i] == "." and i != len(sentence)-1: sentence = sentence[:i+2] + sentence[i+2].upper() + sentence[i+3:] return sentence print(capitalize(sentence))

The elements in a dictionary are not stored in a specific order. Therefore, a dictionary is not a(n) ________.

sequence

A(n) ________ is an object that holds multiple unique items of data in an unordered manner.

set

Create a dictionary that maps the first n counting numbers to their squares. Associate the dictionary with the variable squares.

squares = {} for i in range(1, n+1) : squares[i] = i * i squares = dict([(i, i*i) for i in range(1, n+1)])

Write a statement that associates t with a tuple that contains the following elements: 42, 56, 7 .

t = (42, 56, 7)

Given a variable temps that refers to a list, all of whose elements refer to values of type float, representing temperature data, compute the average temperature and assign it to a variable named avg_temp. Besides temps and avg_temp, you may use two other variables -- k and total.

total = 0.0 for k in temps: total += k avg_temp = total / len(temps)

You would typically use a for loop to iterate over the elements in a set.

true

Each element in a dictionary view is a ________.

tuple

The ________ of two sets is a set that contains all the elements of both sets.

union

Which method can be used to add a group of elements to a set?

update

Given the string line, create a set of all the vowels in line. Associate the set with the variable vowels.

vowels = set() for c in line : if "aeiou".find(c) >= 0 : vowels.add(c) vowels = set(c for c in line if "aeiou".find(c) >= 0)

The code below asks the user "Do you want to repeat the program or quit? (R/Q)". A loop should repeat until the user has entered an R or Q (either uppercase or lowercase). Replace the second line with the appropriate while statement. again = input('Do you want to repeat ' + ⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅'the program or quit? (R/Q) ') # What goes here? ⋅⋅⋅⋅again = input('Do you want to repeat the ' + ⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅'program or quit? (R/Q) ')(Note: The ⋅⋅⋅⋅ symbols represent indentation.)

while again.upper() != 'R' and again.upper() != 'Q':

What is the correct structure to create a dictionary of months where each month will be accessed by its month number (for example, January is month 1, April is month 4)?

{ 1 : 'January', 2 : 'February', ... 12 : 'December' }

What will be displayed after the following code executes? (Note: the order of the display of entries in a dictionary are not in a specific order.) cities = {'GA' : 'Atlanta', 'NY' : 'Albany', 'CA' : 'San Diego'} if 'FL' in cities: del cities['FL'] cities['FL'] = 'Tallahasee' print(cities)

{'GA': 'Atlanta', 'NY': 'Albany', 'CA': 'San Diego'}

Write a statement that associates s with a set that contains the following elements: 23, 42, -11, 89.

s = set([23,42,-11,89])

What will the following code display? mylist = [1, 2, 3, 4, 5] print(mylist[2:])

[3, 4, 5]

What is the number of the first index in a dictionary?

Dictionaries are not indexed by number.

What will the following code display? mylist = ['mercury', 'venus', 'earth', 'mars', ⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅'jupiter', 'staurn', 'uranus', 'neptune'] print(mylist[0::2]) (Note: The ⋅⋅⋅⋅ symbols represent indentation.)

['mercury', 'earth', 'jupiter', 'uranus']

The difference of set1 and set2 is a set that contains only the elements that appear in set1 but do not appear in set2.

True

The set remove and discard methods behave differently only when a specified item is not found in the set.

True

Given the dictionary, d, find the largest key in the dictionary and associate the corresponding value with the variable val_of_max. For example, given the dictionary {5:3, 4:1, 12:2}, 2 would be associated with val_of_max. Assume d is not empty.

axKey = list(d.keys())[0] for k in d.keys() : if k > maxKey : maxKey = k val_of_max = d[maxKey]

The variable planet_distances is associated with a dictionary that maps planet names to planetary distances from the sun. Write a statement that deletes the entry for the planet name "Pluto".

del planet_distances["Pluto"]

Assume you have two lists list1 and list2 that are of the same length. Create a dictionary that maps each element of list1 to the corresponding element of list2. Associate the dictionary with the variable dict1.

dict1 = {} for i in range(len(list1)) : dict1[list1[i]] = list2[i] dict1 = dict([(list1[i], list2[i]) for i in range(len(list1))]) dict1 = dict([(list1[i], list2[i]) for i in range(len(list2))])

To write an object to a file, you use the ________ function of the ________ module.

dump, pickling

Write an if statement using the in operator that determines whether 'd' is in my_string. A print statement that might be placed after the if statement is included.

if 'd' in my_string:

Write the first if statement to complete the code below. The block should display "Digit" if the string referenced by the variable ch contains a numeric digit. Otherwise, it should display "No digit." # What goes here?⋅⋅⋅⋅print('Digit') else:⋅⋅⋅⋅print('No digit') (Note: The ⋅⋅⋅⋅ symbols represent indentation.)

if ch.isdigit():

A loop counts the number of uppercase characters that appear in the string referenced by the variable mystring. Replace the second statement with the appropriate if statement.for letter in mystring: ⋅⋅⋅⋅# What goes here? ⋅⋅⋅⋅count += 1 (Note: The ⋅⋅⋅⋅ symbols represent indentation.)

if letter.isupper():

Given: a variable current_members that refers to a list, and a variable member_id that has been assigned a value. Write some code that assigns True to the variable is_a_member if the value assigned to member_id can be found in the current_members list. Otherwise, assign False to is_a_member. In your code, use only the variables current_members, member_id, and is_a_member.

if member_id in current_members: is_a_member=True else: is_a_member=False is_a_member = member_id in current_members

In order to avoid KeyError exceptions, you can check whether a key is in the dictionary using the ________ operator.

in

To determine whether or not a key is included in a dictionary, or if an element is included in a set, you can use the ________ operator.

in

Given a dictionary d, create a new dictionary that reverses the keys and values of d. Thus, the keys of d become the values of the new dictionary and the values of d become the keys of the new dictionary. You may assume d contains no duplicate values (that is, no two keys map to the same values.) Associate the new dictionary with the variable inverse.

inverse = {} for key in d.keys() : val = d[key] inverse[val] = key

The ________ method returns all of a dictionary's keys as a dictionary view.

items

Given that t refers to a tuple, write a statement that assigns the value of its first element to k.

k = t[0]

Given variables first and last, each of which is associated with a string, representing a first and a last name, respectively. Write an expression whose value is a string that is a full name of the form "Last, First". So, if first were associated with "alan" and last with "turing", then your expression would be "Turing,Alan". (Note the capitalization! Note: no spaces!) And if first and last were "Florean" and "fortescue" respectively, then your expression's value would be "Fortescue,Florean".

last[0].upper() + last[1:] + "," + first[0].upper() + first[1:]

Given a list named play_list, write an expression whose value is the length of play_list.

len(play_list)

Many companies use telephone numbers like 555-GET-FOOD so the number is easier for their customers to remember. On a standard telephone, the alphabetic letters are mapped to numbers in the following fashion: A, B, C: 2 D, E, F: 3 G, H, I: 4 J, K, L: 5 M, N, O: 6 P, Q, R, S: 7 T, U, V: 8 W, X, Y, Z: 9 Write a program that asks the user to enter a 10-character telephone number in the format XXX-XXX-XXXX. The application should display the telephone number with any alphabetic characters that appeared in the original translated to their numeric equivalent. Sample RunEnter a phone number to be translated:555-GET-FOOD ↵555-438-3663↵

phoneNumber = input("Enter a phone number to be translated:") def replace(num): if num == 'A' or num == 'B' or num == 'C': return '2' elif num == 'D' or num == 'E' or num == 'F': return '3' elif num == 'G' or num == 'H' or num == 'I': return '4' elif num == 'J' or num == 'K' or num == 'L': return '5' elif num == 'M' or num == 'N' or num == 'O': return '6' elif num == 'P' or num == 'Q' or num == 'R' or num == 'S': return '7' elif num == 'T' or num == 'U' or num == 'V': return '8' elif num == 'W' or num == 'X' or num == 'Y' or num == 'Z': return '9' else: return num for i in range(0, len(phoneNumber)): phoneNumber = phoneNumber[:i]+replace(phoneNumber[i])+phoneNumber[i+1:] print(phoneNumber)

What is the process used to convert an object to a stream of bytes that can be saved in a file?

pickling

Given that play_list has been defined to be a list, write a statement that sorts the list.

play_list.sort()

Given that play_list has been defined to be a list, write an expression that evaluates to a new list containing the elements at index 0 through index 4 in play_list. Do not modify play_list.

play_list[0:5]

Assume that play_list refers to a non-empty list, and that all its elements are integers. Write a statement that associates a new value with the first element of the list. The new value should be equal to twice the value of the last element of the list.

play_list[0] = 2*play_list[-1]

Given that k and j each refer to a non-negative integer and that play_list has been defined to be a list with at least j+1 elements, write an expression that evaluates to a new list containing all the elements from the one at index k through the one at index j of list play_list. Do not modify play_list.

play_list[k:j+1]

Write a statement that defines plist as the list containing exactly these elements (in order): "spam", "eggs", "vikings" .

plist = ["spam", "eggs", "vikings"]

Write statement that defines plist to be a list of the following ten elements: 10, 20, 30, ..., 100 in that order.

plist = [10,20,30,40,50,60,70,80,90,100]

Write a statement that defines plist to be the empty list.

plist = []

Given a variable named plist that refers to a list, write a statement that adds another element, 5 to the end of the list.

plist.append(5)

Given that k refers to an integer that is non-negative and that plist1 has been defined to be a list with at least k+1 elements, write a statement that defines plist2 to be a new list that contains all the elements from index k of plist1 and beyond. Do not modify plist1.

plist2 = plist1[k:]

Given that plist1 and plist2 both refer to lists, write a statement that defines plist3 as a new list that is the concatenation of plist1 and plist2. Do not modify plist1 or plist2.

plist3 = plist1 + plist2

Given that plist has been defined to be a list of 30 elements, add 5 to its last element.

plist[-1] += 5

Given a variable plist, that refers to a non-empty list, write an expression that refers to the first element of the list.

plist[0]

Assume that a variable named plist refers to a list with 12 elements, each of which is an integer. Assume that the variable k refers to a value between 0 and 6. Write a statement that assigns 15 to the list element whose index is k.

plist[k] = 15

Which method would you use to get the value associated with a specific key and remove that key-value pair from the dictionary?

pop


संबंधित स्टडी सेट्स

Exam 1: Blood Flow Through the Heart (put in the correct order)

View Set

Corporate Finance Exam 1 - Chapter 2 Quiz

View Set

Chapter: Individual Life Insurance Contract - Provisions and Options

View Set

Chapter 6 Networking and OS; Multiple Choice Questions

View Set