Final Practice Questions Set 1
Final Practice Questions Set 1
2.
Lists and tuples are pretty similar, but there are two major differences. (2 points)
a)
Obviously, they're syntactically different; write a syntactically correct tuple, called t, that contains the values 1, 2, and 3 and a
syntactically correct list , called lst, that contains the values 1, 2 and 3.
b)
What can you do with a list that you can't with a tuple ?
Your computer became sentient, and it decided that it wanted to become an artist. Its first work of art is the code below. In the
space to the right, draw the ASCII art image that is printed out by the program (with a character per box; leave the box blank if the
character is a space). (2 points)
s = ""
numbers = (5, 10, 15, 20, 25)
for i in range(5):
row = ""
#(indentation fixed from previous version)
for j in numbers:
if j % 2 == 1:
row += "x"
else:
row += "\\"
s += row + "\n"
print(s)
3.
You've been hired to write an English to Spanish translator by someone that loves cats and dogs. Write a function called
en_espanol that translates English words into Spanish words. You'll write this two ways, but both will do the following:
Your function should take one argument the word to be translated. It should return the translated word.
If the word is 'cat' in any casing ('Cat', 'CAT', 'cAt', etc.) return 'gato', and if the word is 'dog' in any casing return 'perro'.
Example usage:
Resulting Output:
print(en_espanol('Cat'))
print(en_espanol('Final Exam'))
gato
no se
4.
Fill in the chart below. Write in Yes, No or N/A based on the attribute in the column header and the type in the left-most column.
Write a syntactically correct literal value for each type in the right-most column. An example row has been filled in. (4 points)
mutable
ordered
compound
syntax
float (float)
No
N/A
No
5.2
int
(integer)
No
N/A
No
str
(string)
list
(list)
dict
(dictionary)
tuple (tuple)
5.
What sequence of numbers would be generated from calling range with the following arguments? (2 points)
(a) range(3)
________________
6.
________________
________________
Bored with games like Scrabble, Words With Friends, and Boggle, you decide to design your own word game. In your game, you
create words from a random set of letters. Your word's length and your inclusion of hard-to-use letters, such as q and z determine
how many points your word is worth. Implement a function to score your words using the rules below. (5 points)
a)
the first thee letters count as one point and each additional letter above three counts as another point
b)
if the word is less than three letters, your word counts as zero points
c)
if the word has one or more q's in it, multiply points by three
if the word has both q'z and z's in it, multiply points by ten (instead of just three or two)
f)
write a function called score_word that takes a string as input and returns an integer representing the score
g)
assume that the input you will get will consist of only lowercase letters (no punctuation, numbers, spaces or uppercase)
h)
example words and their corresponding scores (make sure you try them all as inputs to your actual implementation):
quiz = (1 + 1) * 10 = 20 points
quits = ((1 + 2) * 3) = 9 points
no = 0 + 0 = 0 points
zip = (1 + 0) * 2 = 2 points
toast = (1 + 2) = 3 points
7.
Read the code in the 1st column. Write the output of the code in the 2nd column, and answer the question in the 3 rd column. No
output and error are both possible. (3 points)
Code
Output
Question
What value is in e?
What value is in b?
b = make_some_noise()
def make_some_noise(noise):
return noise + '!' * 4
result = make_some_noise('pop')
print(noise)
8.
b)
Name ___________________
Reason ________________________________________________
Name ___________________
Reason ________________________________________________
Use exception handling to prevent an error from happening when the user types in 'foo'. Instead of an error, the program
should write out, I don't have that data!. Use arrows or cross out and rewrite code if indentation is required.
person = {'first':'Alice', 'last':'Abel', 'middle':'A'}
response = input('What data would you like?')
print(person[response])
9.
Imagine that the code in the first column is executed line-by-line. After each line is executed, examine the state of the variables a,
b, c and d, and write the values that are bound to them in the columns to the right of the code. The variables may contain a value,
may not yet exist (N/A), or may have a value that hasn't changed from the previous value (unchanged).
All of the N/A and unchanged items have been filled in (this can be used as a hint!). Fill in the remainder of the missing values.
(4 points)
code
N/A
N/A
N/A
N/A
N/A
N/A
N/A
b = a.pop()
b['y'] = 24
unchanged
c = b.get('z', 10)
unchanged
unchanged
N/A
d = a.extend([3, 8])
unchanged
unchanged
del a[-1]
unchanged
unchanged
unchanged
a)
b)
Write out two different ways to remove the number 5 from the above list, numbers. Do this in place; this means that you
cannot overwrite the numbers variable using assignment.(1 point)
_______________________________________________________
_______________________________________________________
Write out two different ways to add the elements from the list, more_numbers, to the other list, numbers, as individual, and
discrete elements (either creating a new list or modifying the existing numbers list). (1 point)
_______________________________________________________
_______________________________________________________
11. Using the two variable declarations below, what is the output of the following lines of code? If the code results in an error, write
error in the space provided. (3 points)
animal = "giraffe"
idx = len("animal")
a) print("animal"[idx])
(a)_____________
b) print(animal[2:])
(b)_____________
c) print(animal[-1] + str(idx))
(c)_____________
d) print(animal[4:(idx * 2)])
(d)_____________
e) print("animal"[-2])
(e)_____________
f) print(animal[idx])
(f)_____________
12. Use the following dictionary to answer the questions below. (2 points)
d = {'x':100, 'y':200}
a)
Write two syntactically correct ways of retrieving the value at key, 'x' from the dictionary, d.
b)
Write a syntactically correct way of adding a new key value pair, 'z':300, to the dictionary, d.
c)
Write a syntactically correct way of removing the element, 'x', from the dictionary d.
13. Complete the code below to draw a triangle with a side of 75 pixels (the triangle can be pointed up or down). (3 points total)
import ____________________________
don = turtle.________________()
wn = turtle.________________()
for i in range(_____________________):
don.__________________________(75)
don.__________________________(120)
wn.mainloop()
14. You have an electronic journal that you'd like to protect with a password, so you wrote a short program. (2 points)
a)
The program continually asks the user (you!) for a password (it's pickles!)...
b)
If the user enters the right password (again, it's pickles), the loop stops, and your journal is printed out to the screen
c)
However, just as you were about to run your program, your cat jumped onto your keyboard and deleted two very important lines.
Now, whatever you enter, you'll still be asked for the password again, even if you got the password right! Fix the program so that
when you enter the right password, the loop stops, and the line that prints out secret journal stuff is executed.
while True:
cmd = input('What's the secret password?\n>')
_____________________________
_____________________________
print('Some super secret journal stuff here')
15. Name two built-in Python modules. For each module, name one function that you can call from that module and what it does.
(2 points)
Module Name:______________ Function:___________________________________________________
Module Name:______________ Function:___________________________________________________
16. Write a function called count_letters. It should take a string as an argument. It should return a dictionary that contains
individual letters as keys and the corresponding counts as values. (4 points)
a)
b)
Consider uppercase and lowercase letters as the same letter, and put them in the key that's the lowercase version of the letter
c)
d)
For example:
s = 'Eeeeaasy!!!'
d = count_letters(s)
print(d)
# output should be similar to
# {'a': 2, 'y': 1, 's': 1, 'e': 4}
17. Because you find yourself computing factorial so often, you decide to write a function that does it for you. Unfortunately, before
you could finish your implementation, you fell asleep, dreaming of exclamation points and unicode snowmen ... and when you
woke up, you found code that wasn't quite right. (3 points)
Wait what's factorial again? Oh yes: n factorial or n! is the product of all non-negative integers less than n. For example, 4
factorial is 4 * 3 * 2 * 1 .
def fact(n):
result = 1
while n > 0:
result = result * n
return result
print(fact(4))
a)
b)
When you run it, what happens? Circle one of the answers below:
Loops forever / eventually crashes;
prints 1 repeatedly
Error
How would you fix the implementation so that factorial is computed appropriately? You can make the fix directly in the code
above.
18. Create a function called flip_sign. It will flip the sign (negative positive, positive negative) of every other number in a list
of numbers, starting with the first. It will do this in place. (4 points)
a)
b)
c)
changing the sign of every other list element, starting with the first
d)
it does not return anything, rather it changes the list passed in in place
the output below shows the expected behavior (note that my_numbers, which is passed in, is changed in place)
my_numbers = [1, 2, 3, 4, 5, 6]
print(my_numbers)
flip_sign(my_numbers)
print(my_numbers)
Results in the following output:
[1, 2, 3, 4, 5, 6]
[-1, 2, -3, 4, -5, 6]
19. What are the values bound to the variables n and points after running this program? (2 points)
n = 0
points = [(1, 2, 3), (4, 5, 1), (1, 2, 1), (2, 2, 2)]
for i in range(2):
x, y, z = points.pop()
n += x * y * z
(1) n______________________________ (2)points___________________________________________
20. Read the code sample in the first column. Answer the questions in the second column. (5 points)
Code
Question
a = 'umxexcusemex!'
b = a.split('x')
c = '8'.join(b)
a = [[[1,2,3],[4,5,6]], [1,2,3,4,5]]
val = a[1].index(4)
print(val // 2)
What code would you use to retrieve the value 6 from a. What is
the output of the program?
def move_car():
for i in range(4):
car['x'] += 20
move_car()
print(car)
s = ''
greeting = 'Hello there!'
for c in greeting.upper():
if c not in 'AEIOU' and c not in s:
s += c
print(s)
21. Create a function called slice_and_splice. It takes a string as an argument. It returns a new string starting with the last half
of the original word and ending with the first half of the word. If the word cannot be split evenly, the last half of the original word
should get the extra letter. See the 'hello' example below. (3 points)
>>> slice_and_splice('hi')
'ih'
>>> slice_and_splice('i')
'i'
>>> slice_and_splice('hello')
'llohe'
>>> slice_and_splice('violin')
'linvio'
22. Cross out all of the statements that are false or evaluate to False. (3 points)
(a) 7 not in ['hi', None, 7, 3]
(f) join and split are both methods called on list objects
(g) 'twelve'.isdigit()
24. You have a file called numbers.txt. It contains the following text:
7,hello,2,8,1,0
2,44
5
23,not a number,11,12
Each item is separated by a comma, each line is separated by a new line. Write a program to read the file and print out
the sum all of the numbers contained in the file. It should ignore items that are not numbers. (5 points)
Hints:
(a) use the built-in function, open, with the appropriate mode, 'r', to read the file
(b) you can iterate over a file object to get every line
or use the read() method to read the entire contents of the file as a string
or use the readlines() method to read the entire contents of the file as a list of strings
or use readline() to read one line at a time (remember to loop forever and break if string is length 0)
(c) use a string method to break up each line into a list
(d) there may be nested loops involved (iterate over every line, itereate over every item in each line)
(e) depending on which method you used for reading the file, you may need to strip off a newline character...