The final exam is comprehensive and will cover the following topics:
Basic Syntax and Types
Conditional Execution
Iteration
Functions
Lists and Strings
Dictionaries, Sets
File I/O
Data Manipu
As with the quizzes, the exam will consist of definitions, short answers, code evaluation, debugging, and programming sections. For the programming section, you will be able to use your computer (but only after you have completed all the other sections).
Below are examples of the type of questions that may be asked on the midterm. It is mean to be representative, rather than exhaustive (ie. there may be questions that show up on the midterm that are not show below).
Briefly define the following terms.
Program:
Interpreter:
Variable:
Syntax Error:
Expression:
Statement:
Boolean Expression:
Exception:
Short Circuit Evaluation:
Infinite Loop:
Immutable:
Function:
Named Argument:
Scope:
Index Operator
KeyError
File Handle
With Statement
Text File
Binary File
CSV
JSON
IOError
Image
**C
What is the result of the each of the following lines of Python code:
print type(1 + 3)
print type(1 + 3.0)
print '1' + 3
print '1' + '3'
What is the result of the following Python code:
x = 1
y = 2
z = x + y
print x, y, z
x = y
y = x
print x, y, z
What is the result of the following Python code:
for i in range(0, 10):
if i < 4:
continue
elif i == 7:
break
else:
print i
print i
What is the result of the following Python code:
def pretty_print_string(s, title=False, sort=False):
if title:
s = s.title()
if sort:
s = ' '.join(sorted(s.split()))
print s
pretty_print_string('python is the best')
pretty_print_string('python is the best', sort=True)
pretty_print_string('python is the best', True, True)
What is the result of the following Python code:
def filter_numbers(numbers, n):
results = []
for number in numbers:
if not number % n:
results.append(number)
return results
for i, v in enumerate(filter_numbers(range(0, 10), 4)):
print i, v
What is the result of the following Python code:
def search(numbers):
is_found = False
index = 0
while index < len(numbers) and not is_found:
if not numbers[index] % 2 and not numbers[index] % 3:
is_found = True
else:
index += 1
return index, numbers[index]
print search(range(3, 9))
print search(range(8, 16))
What is the result of the following Python code:
def add_data(data, x):
data.append(x)
def clear_data(data):
data = []
data = []
add_data(data, 7)
print data
add_data(data, 1)
print data
clear_data(data)
print data
add_data(data, 4)
print data
What is the result of the following Python code:
print 'go irish'.split()[0]
print 'go irish'.split()[1][-1]
print 'go irish'.split()[:1]
print 'go irish'.split()[::-1]
What is the result of the following Python code:
d = {}
s = 'banana band'
t = ''.join(s.split())
for l in t:
d[l] = d.get(l, 0) + 1
for k in sorted(d, key=d.get, reverse=True):
print d[k], k
What is the result of the following Python code:
d = {'boy': 'garcon', 'girl': 'fille'}
print d['boy']
print d['fille']
print d.get('man')
print d.get('man', d.get('boy'))
Given the following "demo.csv" file:
Nicolas Ardito Barletta,narditob@nd.edu,SC,ACMS / MACT / MCDT,BS,03,UG,AS
Kevin Barrett,bkevin@nd.edu,AL,DESN / MCDT,BA,03,UG,AS
Luke Berning,lberning@nd.edu,BA,ACCT / MCDT,BBA,04,UG,AS
Emily Burns,eburns7@nd.edu,SC,ACMS / ROS2 / MCDT,BS,03,UG,AS
Loren Chen,lchen3@nd.edu,AL,DESN / MCDT,BA,02,UG,AS
Peter Chiang,pchiang@nd.edu,EG,CHEG / MCDT,BSCH,02,UG,AS
Jordyn Coyne,jcoyne1@nd.edu,BA,ITM / MCDT,BBA,03,UG,AS
What is the result of the following Python code:
Years = {}
for line in open('demo.csv'):
data = line.strip().split(',')
year = int(data[5])
Years[year] = Years.get(year, 0) + 1
for year, count in sorted(Years.items()):
print year, count
What is the difference between a while
loop and a for
loop? Give
two examples where we would prefer one over the other.
What is the difference between a fruitful function and a void function? How do we make a function fruitful? How would you utilize the outputs of a fruitful function?
What is the difference between a list
and a string
? What can you do
with a list that you can't do with a string and vice versa?
What is the difference between a global variable and a local variable? Give an example of each.
What is the difference between a list
, a dict
, and a set
? For each
data structure, identify a use case for which it is best suited for.
Write some Python code that does each of the following:
a. Reads all the contents of a file into a single string.
b. Reads all the contents of a file into a list of strings.
c. Prints out the contents of a file line-by-line.
d. Lists the contents of a directory.
What are the four basic operations you can perform on a file (handle)?
Why should you close a file after opening it?
What are some reasons why an open would fail?
What are some advantages to using the csv
Python module for parsing
comma-separated-values, rather than simplying doing str.split
?
Convert the following Python code to use a while
loop instead of a for
loop:
numbers = [5, 4, 7, 0, 1]
count = 0
for number in numbers:
if number:
break
count += 1
Search: Convert the search
function above to use a for
loop and to take an additional argument find_all
which by default is set
to False
. If find_all
is True
then the search function should return a
list of all numbers that match the criteria.
Correct the following Python code:
volume of sphere = (4/3) math.pi (r^3)
print volume of sphere
The Python code below is suppose to count all of the even numbers between 1 and 100 (inclusive) that are also a multiple of 5, but it contains some errors. Identify and fix the errors:
while i < 100:
if i % 2 or i % 5:
total + 1
print total
The Python code below is suppose to determine if the given list of
numbers
is sorted. That is, it should return True
if each item in the
list is less than the next item. Unfortunately, there are a few errors in
the code below. Identify the errors and fix the code.
def is_sorted(numbers):
''' Return whether or not the list of numbers is sorted '''
for i in numbers:
if numbers[i] < numbers[i + 1]:
print 'True'
else:
print 'False'
The Python code below is suppose to use a dict
to determine the most
frequenctly used word in a string of text, but it contains some errors.
Identify and fix the errors:.
def most_frequent_word(text):
counts = {}
for word in text:
counts[word] = counts[word] + 1
most = 0
for key, value in enumerate(counts):
if value < counts[most]:
most = value
return most
Given the above "demo.csv" file, the code below is trying to determine a count of all the programs (e.g. ACMS, MACT, etc.), excluding MCDT, represented by the students not in the business (eg. BA) college:
Programs = {}
for line in open('demo.csv'):
data = line.strip().split(',')
college = data[3]
programs = data[4]
if college == 'BA':
break
for program in programs:
program = program.strip()
programs[program] += 1
print Programs
The output of the program should be:
{'ACMS': 2, 'CHEG': 1, 'DESN': 2, 'MACT': 1, 'ROS2': 1}
Unfortunately, there are errors. Identify these bugs and fix them.
The Python code below is suppose to determine if the given list of data
is in descending order. That is, it should return True
if each item in the list
is greater than or equal to the next item. Unfortunately, there are a few
errors in the code below. Identify the errors and fix the code.
def is_descending(data):
''' Return whether or not a list is in descending order '''
for index in data:
if data[index] < data[index + 1]:
print 'False'
else:
print 'True'
The Python code below is suppose to return the number of times a word
appears in the text
. Unfortunately, there are a few errors in the code
below. Identify the errors and fix the code.
def count_word(text, target, case_sensitive=False):
''' Return number of times word appears in text '''
if case_sensitive:
text = text.lower()
for word in text:
count = 0
if word == target:
count + 1
print count
Write Python code that requests the base
and height
of a triangle
from the user, computes the area of a triangle, and then prints the result:
Base? 4
Height? 2
The area of a triangle with base 4 and height 2 is 4.
Given a list of random integers, numbers
, write Python code that
computes the sum of all the numbers between a
and b
(inclusive) and
prints the resulting total.
Write Python code that prints 'Yeah' if a number n
is between the values
a
and b
(inclusive). Otherwise, print 'Nope'.
Write Python code that generates n
random numbers (between 0
and
9
), counts the number of odd and even numbers, and then prints out the
totals.
Write Python code that computes the list of the even numbers between 0
and 100
. that are also a multiple of 7
.
Write Python code that simulates rolling a die until we a 6
and
reports how many rolls it took.
Write a Python function called read_password
:
def read_password(password, prompt='Password?', max_attempts=3):
''' Returns whether or not user has entered the correct password. '''
This function provides the user with the
prompt
and reads the input from the user. This input is checked against thepassword
. If the user input and thepassword
match, thenTrue
is returned. This is attemptedmax_attempts
times and thenFalse
is returned if there is no match.
Write a Python function called filter_range
:
def filter_range(numbers, a, b):
''' Return all numbers between a and b (inclusive) '''
>>> filter_range([7, 1, 5], 0, 5)
[1, 5]
Given a list
numbers
and two integersa
andb
, return a list of all items innumbers
that are betweena
andb
(inclusive).
Write a Python function called count_word
:
def count_word(text, word, case_sensitive=False):
''' Return number of times word appears in text '''
>>> count_word('Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo', 'buffalo')
8
>>> count_word('Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo', 'buffalo', True)
5
Given a string
text
and a stringword
, this function returns the number of timesword
appears intext
. Ifcase_sensitive
isTrue
, then letter case must be factored in comparing strings.
Use a dict to write a function called hacker_speak
that translates a
string of text into 13375p34k by replacing letters in the text according to the
following rules:
def hacker_speak(text):
''' Returns string of text translated into 13375p34k
a -> 4 Examples:
e -> 3 >>> hacker_speak('leetspeak')
l -> 1 '13375p34k'
o -> 0
s -> 5 >>> hacker_speak('pnutzhaxor')
t -> 7 'pnu7zh4x0r'
'''
Note: leetspeak is just a kewl/stupid meme people on the Internet
do where certain letters in a string are replaced with numbers. For
instance, in the example above, the letters a
and o
in pnutzhaxor are
replaced with 4
and 0
to form pnutzh4x0r
.
Write a Python function called read_integer
:
def read_integer(minimum, maximum, max_attempts=3):
''' Return int from the user between `minimum` and `maximum` '''
>>> read_integer(0, 9)
Please enter a number between 0 and 9: 10
Please enter a number between 0 and 9: 1
1
This functions provides the user with the prompt "Please enter a number
between minimum and maximum", and reads the input from the user. This
input is checked to ensure that the number is between minimum
and
maximum
(inclusive). If the input is valid, then the read integer is
returned. This is attempted max_attempts times
and then None
is
returned.
Write a Python function called filter_multiples
:
def filter_multiples(numbers, multiples):
''' Return all the numbers in `numbers` that are multiples
of the numbers in `multiples`
'''
>>> filter_multiples([1, 2, 3, 4, 5, 6, 7, 8, 9], [3, 5])
[3, 5, 6, 9]
Given a list of numbers and a list of multiples
, this function returns
a list of all of the items in numbers
that are multiples of the items
in multiples
.
Write a Python function that determines if a color is found in an image.
Write a Python function that returns the total number of different colors in an image.
Write a Python function that copies an image to a new image.