0% found this document useful (0 votes)
3 views

Practice Final

The document is a practice final exam for a Python programming course, consisting of two sections worth a total of 100 points. Section 1 includes four questions related to Python code analysis, while Section 2 requires students to write Python programs based on given prompts. The exam emphasizes reasoning over memorization and includes a glossary of terms for reference.

Uploaded by

k2n2pvtltd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Practice Final

The document is a practice final exam for a Python programming course, consisting of two sections worth a total of 100 points. Section 1 includes four questions related to Python code analysis, while Section 2 requires students to write Python programs based on given prompts. The exam emphasizes reasoning over memorization and includes a glossary of terms for reference.

Uploaded by

k2n2pvtltd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Practice Final Exam for V22.

0002
December, 2015

Name:
Net ID

There are 2 sections, the first section is worth 50 points and the second section is worth 50 points, for a total of 100.
Answer all 4 questions in Section 1. Answer 2 out of the 3 questions in Section 2.
It is essential that you PUT YOUR NAME AND NET ID ON ALL TEST MATERIALS. It can be difficult to identify
the author of an unsigned test and it would be better to avoid this problem.
There is a GLOSSARY OF TERMS at the end of the test. Please feel free to look up some of the basics in this
glossary. I will also answer any reasonable look-up style questions as I am more interested in your ability to
reason than your ability to memorize.

Section 1: (50 points) Each example consists of Python code, followed by questions and places to fill in answers. Please
read all questions carefully and answer them as precisely as possible. Assume that there are no bugs in the code that will
make the system crash, although the code may not solve a problem perfectly. If you find anything that you think is a
bug, there is either a typo (and I should fix it for everyone) or you are mistaken.
Sample Question A:

output = ’1’+’1’

Question: What is the value of the variable output?


Answer: ’11’
Note: Attention to detail is important. The quotes indicate that it is a string. Partial credit is possible. For example,
leaving out the quotes would have lost just a little bit, but answering 2, would have resulted in an incorrect answer.

Question 1

def string_reverse(instring):
output = ’’
for num in range(len(instring)):
output=output+instring[0-(num+1)]
return(output)

def double_reverse(inlist):
for index in range(len(inlist)):
inlist[index]=string_reverse(inlist[index])
inlist.reverse()

in_list = [’cat’,’dog’,’mouse’]

def main():
double_reverse(inlist]

main()

Question: After the above code executes, what is the value of the variable inlist?

1
Question 2

def tack_on_str_positions(instring):
output = ’’
for index in range(len(instring)):
output =output+str(index)+instring[index]
return(output)

def tack_on_list_position(list_of_strings):
output = []
for index in range(len(list_of_strings)):
output.append(str(index)+’_’+list_of_strings[index])
return(output)

def analyze_list_of_strings(list_of_strings):
output = []
for item in list_of_strings:
output.append(tack_on_str_positions(item))
return(tack_on_list_position(output))

output = analyze_list_of_strings([’cat’,’dog’,’mouse’])

Question: After the above code executes, what is the value of the variable output?

2
Question 3

def checking_ducks_in_a_row(input_list):
output = []
plural = False
for item in input_list:
item = item.lower()
bird_type = ’other’
if item[-1] == ’s’:
plural = True
check_item = item[:-1]
elif item == ’geese’:
plural = True
check_item = ’goose’
else:
plural = False
check_item = item
if check_item in [’duck’,’drake’,’duckling’,’mallard’,’widgeon’]:
bird_type = ’duck’
elif check_item in [’goose’,’gander’,’gosling’,’greylag’,’brant’,’honker’]:
bird_type = ’goose’
else:
raise Exception(item+’ is not a type of duck or goose! Revise and start
record = [item,bird_type]
if plural:
record.append(’multiple’)
else:
record.append(’single’)
output.append(record)
return(output)

test_1 = [’duck’,’mallards’,’geese’,’widgeon’,’honkers’]
test_2 = [’ducklings’,’mallard’,’pigeon’]

Question: Given two function calls to checking ducks in a row, the first with test 1 as an argument and the second with
test 2 as an argument, exactly what would happen? If a new list is returned, indicate what that list would be. If an
exception would be raised, indicate that this would be an error and provide the error message.

Answer for checking ducks in a row(test 1):

Answer for checking ducks in a row(test 2):

3
Question 4

def get_lab_id(record,old_id=False):
if old_id:
return(old_id+’X’)
else:
id_num = ’’
for field in record:
if isinstance(field,str):
id_num = id_num+field[0]
elif isinstance(field,int):
if field>99:
field = field//10
id_num = id_num+str(field)
elif isinstance(field,float):
field = str(field)
id_num_list = field.split(’.’)
id_num = id_num+str(id_list[0])
return(id_num)

def classify_record(record):
record.reverse()
id_num = get_lab_id(record)
while id_num in lab_record_dictionary:
id_num = get_lab_id(record,old_id=id_num)
record.append(id_num)
record.reverse()
lab_record_dictionary[id_num]=record

def categorize_lab_specimens(list_of_records,outfile):
import os
global lab_record_dictionary
lab_record_dictionary = {}
for record in list_of_records:
classify_record(record)
list_of_records.sort()
with open(outfile,’w’) as outstream:
for record in list_of_records:
outstring = record[0]
for field in record[1:]:
outstring = outstring+’\t’+str(field)
outstring = outstring+os.linesep
outstream.write(outstring)

def main():
records = [[’dutch elm’,50,5000,’Australia’],[’Bengal Tiger’,10,800,’India’],\
[’Brenda Thompson’,10,80,’Indiana’]]
categorize_lab_specimens(records,’specimens.tsv’)

Question: Write out lines as they would appear in the specimens.tsv file. Indicate tabs as spaces a few characters long.

4
Figure 1: Result of write tally(199)

Section 2 (50 points): Answer 2 of the 3 questions in this section, writing Python programs as specified. If you choose
to answer all 3 questions, please indicate which ones you would like to count for the test.
All questions are meant to handle general cases. If there are variables used as sample input parameters, please do
not write programs that only handle those sample values. They should handle all inputs of that type, e.g., if the input
parameter is a list of lists of the form [[’fish’,1,2,3][’dog’,4,5,6]], that is an example of a list of records, where the first
field of each record is a string, and the remaining fields are integers. Depending on the problem, records may or may not
be limited to 4 items.
If variables or functions are provided for your use in the answer, you can use the name of these variables and call
these functions without re-copying them into your answer.

Question 5: Write a program using the turtle package. Given a number less than 1000, the turtle program should draw
tally marks representing that number. Figure 1 illustrates tally marks corresponding to the number 199. Tally marks
divide up a number into units of 5. Each unit of 5 consists of a sequence of 4 vertical lines, with one diagonal line cutting
across from the top of the first line to the bottom of the last line. The final sequence may represent fewer than 5 as that
number of vertical lines, without the diagonal, e.g., 4 is represented as 4 lines, 3 as 3 lines, etc.
Your program should begin with the turtle at position -300,0. Each vertical lines should be 20 units high and there
should be a space of 10 between vertical lines within a group. There should be a distance of 20 between groups.
If the program ends a block of 5 and the X position is greater than 280, the program should advance to the next line
of tally marks. This means that the program should go to the same X start position (-300), but 30 lower: (-300,-30) for
the second line, (-300, -60) for the third line, etc.

5
Question 6: Write a program that determines the value of a roll of five dice in a game, which I will call Roll ’em. The
player rolls five dice, each using the following function:

def die_roll():
import random
return(random.randint(1,6))

The program must identify the type and value of the hand. Types of hands are defined along with their point values, as
follows (in order from highest to lowest).

1. five of a kind: five instances of the same number (60 points)

2. four of a kind: four instances of the same number (50 points)

3. full house: three instances of one number and two instances of another number (40 points)

4. straight: the roll includes five consecutive numbers in any order, e.g., 2,4,3,1,5 is a valid straight. (35 points)

5. three of a kind: three instances of the same number (30 points)

6. two pairs: two instances of one number and two instances of another number (20 points)

7. pair: two instances of the same number (10 points)

8. high: if none of the above, the value is determined by the highest roll, e.g., if the highest roll is 5, then the value
of the roll is 5.

Extra credit: Complicate the above game by allowing the player to have one additional turn where they can reroll upto
three dice. Add a computerized player that will also have this option, but whose choice is determined automatically. The
computer will never reroll if it gets five of a kind or a straight and it will not reroll dice that are part of a grouping (pair,
three of a kind, four of a kind, five of a kind).

6
Question 7: Write a program that reads in a text file and counts instances of the different characters in the file, storing
the frequency information in a dictionary.
Then the program should sort the keys of the dictionary and write one entry for each key in an output file using any
format you want. (use the DICT.keys() method to identify the keys of the dictionary; use the list function to convert it to
a list; and use list.sort() to sort the list.)
For the space character, print ’SPACE’ rather than the space character (as this will make it easier to read the file).
Similarly, if a character is unprintable, write ’Unicode’, followed by its unicode value instead of the character. The
method string.isprintable() has a value of True if a character is printable and False otherwise, e.g., os.linesep.isprintable()
evaluates to False. Sample lines from an output file that uses .tsv format:

Unicode 10 16
SPACE 142
" 2
( 2
) 2
,28
-4
. 7
A 2
C 1

7
Basic Stuff to Look Up for the Test

1. Some Basics

• return(X) causes the current function to exit and cause the expression represented by the function
call to evaluate as X. For example given the following steps, the value of output would be 5:
def add(num1,num2):
return(num1+num2)
output = add(2,3)
• print(X) prints X to the screen. This is only for the benefit of the user. It is not useful for having
programs interact.
• The parameters of a function are the local variables inside of the parentheses in the function defini-
tion. They are useful when you have functions call functions.
• input(prompt) is used to ask a human being a question so that a program can interact with a
human being. This is useful when you want a human being to enter information interactively. input
statements should be used only when human interaction is appropriate. input statements return a
string corresponding to what the user typed in. It may be necessary to convert this string to some
other data type, e.g., an integer (with int) or a float (with float).
• The operator + will add two numbers or concatenate two strings
• The operator * will multiple two numbers or print a string some number of times.

2. sequences
• object made up of other objects in an order
• the function len(sequence) returns the number of items in the sequence
• the operator in tests for membership in sequence, e.g., (’a’ in ’abc’) would have the value True.
• sequences are used in for loops (see below)
• indices and slices
– Indices in a sequence are numbers from zero to the length of the string. Zero refers to the
position before the first item in the string and the length of the string refers to the position fol-
lowing the last item. Thus each item in the sequence are between two consecutive indices. For
example, the subscripted numbers indicate indices for the string The book: ’0 T1 h2 e3 4 b5 o6 o7 k8 .
Similarly, the indices in [0 ’The’,1 ’book’,2 is,3 ’there’4 ] indicate positions in the list [’The’,
’book’, ’is’,’here’].
– sequence[num] indicates an element in a sequence beginning at num (a number from zero to
one less than the length of the string), e.g., ’The book’[4] evaluates to ’b’; [’The’, ’book’,
’is’,’here’][0] evaluates to ’The’.
– sequence[num1:num2] indicates a subsequence beginning at position num1 and ending at
num2,e.g., ’The book’[4:6] evaluates to ’bo’; [’The’, ’book’, ’is’,’here’][0:2] evaluates to
[’The’, ’book’].
– Leaving out the number before the colon suggests that a subsequence begins at the beginning
of the sequence and leaving out the number after the colon suggests that the subsequence ends
at the end of the list. Thus ’The book’[:3] evaluates as ’The’ and [’The’, ’book’, ’is’,’here’][2:]
evaluates as [’is’,’here’].
• ranges
– range(5) is approximately equivalent to [0,1,2,3,4]
– range(1,5) is approximately equivalent to [1,2,3,4]
• Strings
– an empty string has zero characters ”

8
– strings are sequences of characters, e.g., ’Hello World!’ consists of the items [’H’, ’e’, ’l’,’l’,
’o’, ’ ’, ’W’, ’o’, ’r’, ’l’, ’d’, ’!’]
– string1.strip(string2) – removes instances of string2 from beginning and end of string. For
example, ’***Hello World***’.strip(’*’) will return ’Hello World’.
– string.split(character) – creates a list by dividing a string at each instances of character. For
example, ’Hello World’.split(’ ’) will return the list [’Hello’,’World’].
– string.lower() converts string to lower case
• Lists
– A list is represented by square brackets surrounding a list of objects, divided by commas, e.g.,
[’A’,’List’,’of’,’Strings’]
– Lists are mutable. Changing a variable pointing to a list, can change the list.
– You can add an object to the end of a list using the append method. For example, suppose
my list = [’a’,’b’,’c’]. Then my list.append(’d’) will add ’d’ to the end of my list, setting it to
[’a’,’b’,’c’,’d’].
– You can change an item in a list as follows: list[index] = newitem, e.g., if my list is set to
[1,2,3], then the statement my list[1] = 57, will change the value of my list to [1,57,3].
3. dictionaries – are sets of key/value pairs used for representing attributes of the keys. For example,
consider the dictionary phonebook = ’Mary’:’212-333-4444’,’John’:’914-444-3333’. The keys Mary
and John are linked to the values ’212-333-4444’ and ’914-444-3333’. This dictionary provides a way
to look up the phone numbers of the named people.
• dictionary[key] – returns value associated with key in dictionary
• dictionary[key] = value – dictionary entry for key to value
• The in operator can be used with dictionaries to check if a key is found, e.g., (name in phone book)
evaluates to True given a dictionary phonebook and some key name such that phonebook[key]
would have a value.
• len(dictionary) – returns the number of key/value pairs found in the dictionary.
4. Division and Modulus
• 5 // 2 == 2
• 5/2 == 2.5
• 5%2 == 1
5. print
• sep – separator between items
• end – printed at the end of print statement
6. for loops
• First Line: for VARIABLE in SEQUENCE:
• VARIABLE is set to each item in the sequence one at a time
• The Indented body repeats once for each item in sequence (for each setting of VARIABLE).
• It is common to exit a loop of any kind by using a return to exit the function.
• It is common to initialize a variable outside a loop (called an accumulator) that then gets incre-
mented inside the loop.
7. while loops
• First line While (BOOLEAN-EXPRESSION):
• The loop keeps executing the indented body until BOOLEAN-EXPRESSION evaluates as False.

9
• If BOOLEAN-EXPRESSION is always True, the loop is endless.
• Typically BOOLEAN-EXPRESSION contains one or more variable(s), such that some values of
these variables (or this variable) cause BOOLEAN-EXPRESSION to evaluate as True and other
values cause it to evaluate as False.
• The body of the loop can change these variables. The loop starts when BOOLEAN-EXPRESSION
is True. Then, under most circumstances, BOOLEAN-EXPRESSION eventually evaluates as False
and the loop halts. For example, if the BOOLEAN-EXPRESSION is stop == False, setting stop to
True inside the loop, will cause the loop to finish.
• It is common to use accumulator variables in a similar manner as with for loops.
8. if statements
• the first line of an if statement consists of if BOOLEAN-EXPRESSION:
• the body of text indented under the first line is executed if the BOOLEAN-EXPRESSION evaluates
to True
• the if statement can be followed by optional elif statements of the same form, except that the first
line begins with elif. Each elif statement is only evaluated if the BOOLEAN expressions in the if
and elif statements leading up to this one are False.
• The block of if and optional elif statements can end with an optional else statement. The first line
is simply else:. The body of text under else executes if the Boolean expressions for all previous if
and elif statements in the sequence evaluate to False.
9. Turtles
• Screen and Turtle objects are created using the commands turtle.Screen() and turtle.Turtle().
• The turtle is initially in the center of the screen facing rightward.
• my turtle.left(degrees) – rotates the my turtle degrees left (from its perspective).
• my turtle.fd(distance) – moves the my turtle distance units forward.
• my turtle.pu() – picks the pen up
• my turtle.pd() – puts the pen down (ready to write)
• my turtle.circle(radius) – creates a circle with radius radius. The circle will be above the direction
the turtle was facing when it started drawing. The turtle will move left and up in a circle and end
up in the same place as before.
• my turtle.goto(X,Y) – (or my turtle.setposition(X,Y)) moves the turtle to the position (X,Y) (and
draws a line from the current position to (X,Y) if the pen is down.
• my turtle.pos() – returns the X and Y values of the current position, e.g., X,Y = my turtle.pos()
10. time.sleep(sec) – pauses for sec seconds (requires the module sleep to be imported)
11. Input/Output
• os – module including global variables like os.linesep (end of line strings: ’\n’ or ’\r\n’) and
os.sep (path separators – forward slash ’/’ or backward slash ’\’).
• Streams – Python objects used for reading files and writing to files.
• instream = open(’my file.txt’,’r’) sets the variable instream to the contents of the file ’my file.txt’.
for loops will treat instream as a list of strings, each ending with os.linesep. For most applications,
it makes sense to remove these.
• outstream = open(’my file.txt’,’w’) sets the variable outstream to an object that will ultimately be
saved as the file my file.txt. The method outstream.write(string) will write a string to that file. It is
a good idea to include os.linesep anywhere you would like a line break in the file as end of lines are
not automatic.

10
• stream.close() will close an opened stream. This ends the connection between Python and a file. In
the case of output streams (like outstream), the content of the stream is written to the file.
• with open(file,’r’) as instream: or with open(file,’w’) as outstream: starts a block in which a stream
is opened. The body of code indented under these statements can read from or write to the stream.
After the block, the stream is closed.
12. Error Handling
• raise Exception(STRING) – raises an exception (causes an error) and prints out STRING.
• Try/Except – To key words that begin blocks, similar to IF/Else statements. If the code indented
under Try: does not cause any error, then the following Except statements are ignored. If an error
is raised, the Except statements can “catch” an error. Rather than error, the code indicated under
Except executes.

11

You might also like