CSE 20
What is the output of this code? for i in range(0, 10, 2): print(i, end=' ')
0 2 4 6 8
What is the output of the following program? def printNums(x=5, y=10, z=20): print(x, y, z) printNums (3 , z=8)
3 10 8
What is the value of j at the end of this program? l = [ 10, 1, 12, 7, 8, 2 ] j = 0 for i in l: i f i < 5: continue j += i
37
What is the value of x? x = 5 + 10∗10 // 10∗∗2
6 (1 point for 6.0)
What is line three of the following code? [1] x = 1 [2] y = 2 [3] # Adding together x and y [4] z = x+y
A comment
What will happen in Python3 when we run this code and why? print 'Hello, world!'
A syntax error will occur because print requires its arguments to be in parentheses. (1 pt for syntax error, 1 pt for why)
What is a logical error?
An error in which the program will complete but the resulting output will be in- valid/unexpected due to a fault in the code. (1pt for stating program will complete, 1pt for stating unexpected output)
What is the result of the expression on line 3? [1] x = [ 1 ] [2] y = [ 1 ] [3] x is y
False
What is the value of z? x = 5 y = 10 z = x > y or x ∗ x < y
False
What is the value of y? x = 'Hello, world!' y = x[: −1]
Hello, world
When should you use inheritence vs. composition in designing classes?
Inheritance should be used when the class being created 'is a' more specialized form of the parent class. Composition should be used the class being created 'has a' an instance of another class.
The user inputs 15. What is printed? x = int(input('Enter a positive integer: ')) y = 20 if x > 20: print('Your number', x) else :print('My number', y)
My number 20
What is the return value of the function call fn(10)? def fn(x): if x > 20: return x
None
The function search linear below searches a sequence xs for a target element. If N is the length of xs, in terms of N write an expression for the worst case running time of search linear using Big O notation. def search linear(xs, target): ''' Find and return the index of target in sequence xs ''' for (i, v) in enumerate(xs): if v == target: return i return −1
O(N) (1pt for correctly using big O notation, 1pt for correct scaling)
What is the value of x? x = 'The' + 'Hare' + 'And' + 'The' + 'Tortoise '
TheHareAndTheTortoise
What is the result of the expression on line 3? [1] x = 1 [2] y = 1 [3] x is y
True
What is the result of the expression on line 3? [1] x = [ 1 ] [2] y = [ 1 ] [3] x == y
True
What gets printed to the screen? print('Welcome to my program.\n\tIt's nice to meet you.')
Welcome to my program. It's nice to meet you.
What happens if you run this code? Why? x = 'Hello, world!' x[0] = 'h' print(x)
You get a runtime error because strings are immutable and the code tries to change a string.
What is the value of x? words = 'once the teacher '. split() def getNumberOfVowelsInString ( string ): vowels = 'AOIEUaoieu' i = 0 for character in string: if character in vowels: i = i + 1 return i x = sorted(words, key=getNumberOfVowelsInString)
[ 'the', 'once', 'teacher' ] (1pt for getting list with word strings in it, 1pt for getting correct order)
Let l = [1,5,8,10,12] be a list of integers. Write a list comprehension to filter l to create a list only containing integers greater than or equal to 8.
[ i for i in l if i >=8]
Read the following code: def fn(s): if len(s) == 0: return '' l = [ s[0] ] for i in range(1, len(s)): if s[i] != s[i −1]: l . append( s [ i ]) return ' '. join ( l ) Write out the return values for each of the following function calls?: [A] fn ( ' ') [ B ] f n ( 'GATTACCA' ) [C] fn([ 'Wow', 'Wow', 'Wow' ])
[A] '' (1pt) [B] 'GATACA' (1pt) [B] 'Wow' (1pt)
What is printed by the following code? def recursive fn(a): print('a is: ' + str(a)) if a > 10: recursive fn(a−10) print('a was: ' + str(a)) recursive fn(20)
a is: 20 a is: 10 a was: 10 a was: 20
What are three types of scope in Python and what are their relative precedence with respect to each other?
built-in < global < local, where x<y indicates that x has lower precedence than y. (1 pt for each correct scope, 1 pt for getting precedence right)
Write a function index(x) which returns a dictionary that gives an index of the words in the string x and their indices. Include a docstring and comments. For example, the following usage should be true: index('I really really love Python') == \ { 'I ':[0] , 'really ':[1 , 2], 'love ':[3] , 'Python':[4] } index('we covered this ') == \ { 'we':[0] , 'covered ':[1] , 'this ':[3] } Rubric: • Correctly define function (1pt) • Includes a reasonable docstring (1pt) • Includes comments (1pt) • Creates dictionary (1pt). • Splits string into word (1pt) • Correctly iterates through words in string (1pt) • Correctly adds new entries to the dictionary (1pt) • Correctly adds new occurrences of a word already seen to the dictionary (1pt) • Returns dictionary (1pt) • Fully working bonus (1pt)
def index(x): ''' Returns a index of the words in the string x as a dictionary. ''' d = {} # Dictionary to progressively build for index, word in enumerate(x.split()): # For each word and its index in x if word not in d: # If word not in dictionary create entryy d[word] = [ index ] else: # Otherwise add word to the dictionary d [ word ] . append ( index ) return d
EXTRA CREDIT Write a function, insertion point(x, l), which returns the point in a sorted list l the element x should be inserted to preserve the sort order. Assume l is sorted in ascending order and that the elements in the list are comparable. The following shows example usage: insertion point(3, [ −1, 2, 5 ]) == 2 insertion point(0, [ −1, 2, 5 ]) == 1 insertion point(100, [ −1, 2, 5 ]) == 3 insertion point(−2, [ −1, 2, 5 ]) == 0 Include helpful comment(s) and a docstring. Below is a model answer. Proposed rubric: • Correctly defines the function (2 pts) • Includes a docstring (1 pts) • Includes comments (1 pts) • Iterates over elements in l (2 pts) • Correctly finds insertion point when point is < len(l). (2pts) • Correctly deals with inserting at the end of the list. (2pts)
def insertion point(x, l): ''' Returns the location x should be inserted in the sorted−ascending list l''' for i, element in enumerate(l): if x <= element : return i return len(l) # Case x is greater than all members of l, insert at end
EXTRA CREDIT Write a function, little sort(l) to sort a Python list l using insertion point(x, l) function described in the previous question. Do not alter l itself, rather return a new list representing the sorted l. Hint: you may find using recursion helpful. You may not use the built-in/list sort functions, or the min or max functions. You may assume the elements in the list are comparable. You need not have answered the previous question correctly to attempt this question, and may assume that insertion point(x, l) is correct. The following shows an example usage: little sort([ 3, 6, 2, −1]) == [−1, 2, 3, 6 ] Below is a model answer. Proposed rubric: • Correctly defines the function (2 pts) • Includes a docstring (1 pts) • Includes comments (1 pts) • Uses insertion point (2 pts) • Correctly sorts the list (4 pts)
def little sort(l): ''' Sorts the list l in ascending order ''' if len(l) == 0: # If the list is empty, return the empty list return [] first = l[0] # Get the first member of l l = little sort(l[1:]) # Sort the sublist l[1:], replacing l i = insertion point(first , l) # Figure out where to insert i in l return l[:i] + [first] + l[i:] # Insert first in l
Write a function num non zero digits(x) to return the number of non-zero digits in the integer x, base 10. You do not need to include comments or a docstring, but can if you want to explain the code. Example usage: num digits(100) == 1 num digits(0) == 0 num digits(12345) = 5 num digits(12005) = 3 Rubric • Correctly define function (1pt) • Correctly calculates if a digit is non-zero (2pts) • Correctly iterates over digits (2pts) • Is fully correct bonus (1pt)
def num non zero digits(x): i = 1 if x % 10 != 0 else 0 # 1 if last digit of x is non−zero else 0 j = 0 if x == 0 else num non zero digits(x//10) #Num digits in x//10 return i + j
Pig latin has two very simple rules: If a word starts with a consonant move the first letter(s) of the word, till you reach a vowel, to the end of the word and add 'ay' to the end. e.g.: • have −→ avehay • cram −→ amcray • take −→ aketay If a word starts with a vowel add 'yay' to the end of the word. e.g.: • ate −→ ateyay • apple −→ appleyay • oaken −→ oakenyay Write a function which takes an English word and returns the pig-latin translation of it. You may assume the word consists only of lowercase alphabet characters. In the case the word is the empty string '' return the empty string. Use comments, include a docstring. Below is a model answer. Proposed rubric: • Correctly defines the function (1 pts) • Includes a docstring (1 pts) • Includes comments (1 pts) • Handles the empty string case (1pts) • Locates position of the first vowel in the word (2pts) • Correctly handles the 'ay' case (2 pts) • Correctly handles the 'yay' case (2 pts)
def pigWord(word): ''' Translates an English word to its pig−latin translation . ' ' ' if len(word) == 0: # Handle empty string case return '' # Find the index of the first non−vowel i = 0 while i < len(word) and word[i] not in 'aeiou': i += 1 return word + 'yay' if i == 0 else word[i:] + word[:i] + 'ay'
Write a function print file(file name) to print out all the lines in a file such that each line is prefixed with the string: i \t−−−> string, where i is the line of the file, starting from 0. Lines of the file should be printed in order and consecutively, without intervening newlines. For example if the file consists of the following string: ' The f i r s t l i n e \nThe second line \nThe third line ' The function would print: 0 −−−>The f i r s t l i n e 1 −−−>The second line 2 −−−>The third line The function should properly close the file when finished. You do not have to provide a docstring or comments. Rubric: • Correctly define function (1pt) • Correctly open file (1pt) • Correctly close file with either close() or with keyword (1pt) • Correctly iterate over lines in file (1pt) • Correctly prints one line per line in file (1pt) • Correctly prints desired output format (1pt)
def print file(file name): with open(file name) as fh: for index, line in enumerate(fh): print('{}\t−−−>{}'.format(index, line), end='')
Further extend the Point class from the previous question so that the following usage will be true: p = Point(5, 10) str(p) == 'x=5, y=10' There is no need to repeat the class definition, just write the appropriate method correctly. Below is a model answer. Proposed rubric: • Defines str () method (1pts) • Uses self correctly (2pts) • Creates correct string (2 pts)
def str ( self ): return 'x={}, y={}'.format( self .x, self .y)
Write a function called 'sum' that returns the sum of its two input arguments, x and y. Include a docstring. Rubric: 1 pt for correct function def, 1 pt for including okay docstring
def sum(x, y): '''Returns the sum of x and y''' return x + y
What is the value of x? x = type(1.0)
float
Write an import statement to add the log10() function from the math module so that the following code will execute without error: log10(100)
from math import log10
Consider the following class: class Point: ''' Represents a pair of 2D coordinates''' def init (self , x, y): self.x = x self.y = y Write a method distance(p) for Point which takes another user-supplied Point and returns the Euclidean distance between them, defined for two points (x1,y1),(x2,y2) as √(x1 − x2)2 + (y1 − y2)2. The following usage should be correct: from math import sqrt p = Point(0, 0) q = Point(5, 10) p.distance(q) == sqrt(5∗∗2 + 10∗∗2) There is no need to repeat the class definition, just write the appropriate method correctly. You may use the sqrt function from the math module providing you import it correctly. Please include a docstring. Below is a model answer. Proposed rubric: • Defines distance method (1pt) • Includes a reasonable docstring (1pt) • Includes self correctly (1pt) • Correctly computes Euclidean distance (2 pts)
from math import sqrt def distance(self , p): ''' Returns the Euclidean distance between this point and another point p''' return sqrt ((p.x − self .x)∗∗2 + (p.y − self .y)∗∗2)
What is the output of this code? for i in range(1, 4): for j in range(1, 4): if i % 2 == 0 and j % 3 == 0: print('i: ' + str(i) + ' j: ' + str(j))
i: 2 j: 3
Write Python to build a set x of the words in a string s.
x = set(s.split())
What is the value of x at the end of this program? x = 5 y = 10 x = y y = 20
x == 10
What are the values of x, y and z? def find character(s, ch, start=0, end=None): '''Find the first occurrence of a given character in a string s and return the position , otherwise , i f not present, return −1 ''' for i in range(start, end if end != None else len(s)): if s[i] == ch: return i return −1 x = find character('once upon a time', 'u') y = find character('once upon a time', 'u', end=4) z = find character('once upon a time', 'u', start=5)
x == 5 y == -1 z == 5
What is different about theta vs. the x and y variables of Point? class Point: theta = 5 def init (x, y): self.x = x self.y = y theta is a class variable, as such there only exists one theta variable shared by all instances of the class.
x and y are object (aka instance) variables, as such there exists unique x and y variables for each instance of the class.
What is the problem with this code? [1] print(x) [2] x = 5
x is defined in line 2 after the print statement in line one which refers to it, x is therefore not in the namespace of line 1
Describe three strategies you can use to debug your code? 1 pt for each of any three:
• Use print statements to inspect the value of variables during execution. • Use a debugger to walk through the running code. • Write unit tests to systematically tests individual portions of the code. • Use assert to check expected conditions during execution. • Carefully reason about the behavior of the code.