cs 303E final exam
what does multiple assignments do
I = J = K = I would be K = I, J = K, and I = J
What is the output of the following code? print('I love', 'CS 303E', end='.') print('It\'s my favorite class!')
I love CS 303E.It's my favorite class!
_3rd_ is a valid variable name.
False
If you have an if-elif statement, then you must also have a corresponding else branch.
False you can have an if-elif without an else
There is no way to include a backslash (i.e. this character → \ ) in a string since the backslash is reserved for escape sequences.
False, you can have a backslash, you just have to escape it (i.e. "\\")
To run a python file in batch mode, you will need to import the corresponding module from within the python interpreter command loop.
False, you run in batch mode by running your whole file from the command line, not by importing within interactive mode
What data type does this output: 6 / 2
Float ( one \ is float, \\ two is integer)
Comparisons between characters are done by comparing their underlying codes.
ASCII
ways to break out of a loop
meeting conditions, breaks, or returns
assignments in python
most important common statement in python ( name = value)
For any given string s, the function calls s.split() and s.split(" ") will return the same list.
T
The expression bool([]) is equivalent to False.
T
Within a class, self.__score is a private variable.
T
If x is a floating point number, then int(x) will always round x to the nearest integer.
False
combining floats produces what
floats
interactive mode
A way of using the Python interpreter by typing commands and expressions at the prompt.
you can print \ by:
"\ \" back slashing it
what overrides order of precedence
( )
rules of naming
- begins with letter or underscore - any use of numbers or letters or symbols after first is fine - case matters - cannot use reserved words - should begin lowercase - camelCasing
what does the range (10, 0, -2) and range (0, 10, 2) return?
10, 8, 6, 4, 2/ 0, 2, 4, 6, 8
Global Variable
A variable that can be used in any part of the program.
local variable
A variable that can only be accessed from a specific portion of a program
Which of the following cannot be sorted using the built-in sort() functionality?
All can be sorted (list of dictionaries, strings, or 2D list]
The values 3 and "3" are equivalent representations of the number three, i.e. after the assignments x = 3 and y = "3" , x and y would hold exactly the same value.
False
logic error
An error in a program that makes it do something other than what the programmer intended. hardest to fix
runtime error
An error that does not occur until the program has started to execute but that prevents the program from continuing.
syntax error
An error that results when an instruction does not follow the syntax rules or grammar of the programming language.
What is short-circuit evaluation?
An expression in which the result is determined without evaluating all of the operands and/or operators (ie. if (A and B) are False, it doesnt matter what B is, this also applies to (A or B))
Binary search will still work correctly even if the input list is unsorted, it justwon't be as efficient as compared to running on a sorted list.
F
If the str method isn't explicitly defined for a class, python will raise an error if you try to print an object of that class.
F
If the we execute the assignment s = "call", then afterward we can change the string to "tall" by adding the line s[0] = 't'.
F
For a given sorted list, it always takes less comparisons/probes to find a given element by binary searching over the list as opposed to searching over the list linearly.
T
What is information hiding and how is it used in python?
Information hiding is the method of hiding the operations behind functions because it matters less how it is able to happen, and more that it can be used. These are used to make programs simpler
What data type does this output: 6 % 2
Int (mod on ints gives ints)
What are immutable data types
Int, Float, String
which is the better programming practice: defining local variables or global variables
Local variable, because they are scoped within a function. Variables should have the smallest scope possible to reduce complexity.
What error is this: print("The square root of x is", x ** 1 / 2)
Logic Error
What should you use to compute a factorial?
Loops
RecursionError : maximum recursion depth exceeded in comparison
Meaning: The runtime stack has overflown - the number of recursive function calls has exceeded the "recursion depth."
lst = [x ** 2 for x in range(100)] print( len(set(lst)) == len(lst) )
Output: True
There are 2 functions A and B. A calls B and B calls A. What are these functions called?
Mutually Recursive Functions
Can you use booleans to compare floats?
No
Is input a reserved or key word in python?
No
Can you use "sum" as a variable name?
No, it is not good practice to use function names as a variable even though it is technically possible
This value is returned implicitly fromfunctions with no explicit return statement.
None
import random lst = [0, 1, 2, 3, 4] result = random.shuffle(lst) print(result)
None
Why is Python called a dynamic language
Python variables do not have associated types
In contrast to an absolute path name, a _______ path name specifies the location of a file based on the current working directory.
Relative
What error is this: print("The square root of x is", math.sqrt(x))
Runtime Error
What's the term for selecting a contiguous subsequence of a sequence
Slicing means to select a contiguous subsequence of a sequence (Ex: strings, lists).
What error is this: print("The number", x, "has no "real" square root.")
Syntax Error
"Hello" is an object in python.
T
Any function which calls itself is considered recursive.
T
Dictionaries cannot have repeated keys.
T
open(filename, mode) What is the name of the object returned by this function call? What is it used for?
The file object that is returned on opening a file is also called a file handle. It can be used within the program to access and interact with the file.
Which of the following is NOT a reason to explicitly close a file after you're finished writing to it?
The file will become corrupted if the program terminates and close wasn't called.
Which of the following is a reason to prefer a recursive implementation to an iterative one for the same task?
The size of the runtime stack allows for more complex calculations to be donerecursively which couldn't be done iteratively.
Which of the following best describes what will happen if we call open("file.txt", "w") but a file named file.txt already exists?
The old file.txt will be overwritten with any new lines we write to the file.
Basic arithmetic operations on floats like addition, subtraction, multiplication, and division are only approximate in python, meaning that for certain calculations the results may have some small error.
True
The expression bool(None) is equivalent to False
True
a = {'hello', 0, 439.23, "world"} print(sum(a))
TypeError: unsupported operand type(s) for +: 'int' and 'str'
reserved words
Words that have predefined meanings that cannot be changed; and, as , assert, break, class, continue, def, del, elif, else, except, false, finally, for, from, global, if, import, in, is, lamda, nonlocal, none, not, or, pass, raise, return, True, try, while, with, yield
DO you need to use explicit print statements in script mode?
Yes! Script (or batch mode) requires prints in the program (xyz.py) in order to run them and output something
whats a predicate in programming?
a boolean valued function - returns singular booleanvalue (True or False) based on given conditions
batch mode
a mode of program execution in which the program scans its data from a previously prepared data file
The part(s) of a recursive function which return an answer directly, without needing to make a recursive call.
base case
what is the zen of python?
beautiful > ugly explicit > implicit simple > complex complex > complicated readability
This function is called whenever a new object is created.
constructor
What value does the following expression evaluate to? 50 % 15 + 30 / 10 + 5
by precedence this is 50 % 15 + 30 / 10 + 5 which is 5 + 30 / 10 + 5which is 5 + 3.0 + 5 which is 8.0 + 5 which is 13.0
what are strings sequences of
characters
IDE
interactive development
myObj = {0: 'A', 1: 'B', 2: 'C'} How will you delete the key-value pair (1, 'B') from this myObj?
del myObj[1]
If x is a variable holding a float, then the statement print(round(x, 2)) will always display the value of x to exactly two decimal places.
false, round only affects the value, not how it's displayed, so e.g. print(round(15, 2))will still just display 15
combining an int and a float produces what
float
What statement should be used to classify a function based on certain conditions
if-elif statements
is this function call legal or illegal: ( x = '3', y = '5', 6, 7)
illegal, positional arguments must come first
Unlike strings which cannot be changed after they're constructed, list objects are
immutable
how to find the zen of python
import this
What is the precedence direction of binary operators
left! for example; (x + y - z + w) would be (((x +y) - z) + w)
Suppose L is a non-empty list of integers. When using the linear search functionfrom the lectures on L to try and find an element that isn't present in the list, howmany comparisons/probes are made?
len(L)
Suppose L is a non-empty, two-dimensional list of integers. Which of the following best describes the type of L[0]?
list of intergers
How many comparisons, on average, does it take to find an element using binary search in a list of n items?
log2(n)
what does simultaneous assignments do
m, n = 2, 3 would be m = 2 and n = 3
variable
named memory location to store values, no associated types,
in the function call f(2, 5, c=4, d=4), while the values for c and d are passed as keyword arguments, the values 2 and 5 are this type of argument.
non default
what does ord(c) and chr(n) do?
ord returns the number equivalent of a letter in ASCII chr returns the letter equivalent of a number in ASCII
libraries in python
os, math, random, and datetime
What are two main differences between print and write?
print inserts a newline at the end of each line, unless specified otherwise (end = ""). write does not add a newline at the end of each line by default. print takes an arbitrary number of arguments and coerces them all to strings; write only takes one string argument
Suppose you're using the Student class from homework 7 and you'd like to print the information corresponding to a particular Student object s. Which of the following is NOT a valid way to display the student?
print(s.___str ())
Object attributes beginning with two underscores are attributes.
private
where is the argument passed through to a function
reference
Which of the following keywords can only be used inside a function?
return
round( ) truncates but does not
return the variable to the nearest variable
What is the precedence direction of assigning variables
right! for example: (x = y = z = 1 >= z) would end up being 1
Suppose s1 and s2 are sets and s1.issubset(s2) is True. Which of the following must also be true?
s2.difference(s1) == set()
end = "." indicates no second line, but what does end = " " mean?
second line
This technique for sorting a list consists of repeatedly finding the smallest element in the unsorted part of the list and swapping it to the beginning.
selection sort
Suppose c is an object of some type and i is a positive integer. For which of the following possible types for c is c[i] never a valid operation?
set
format() returns what data type
string
what is documentation
the act of leaving #notes and headers to clarify your code
precedence order
unary + or -, **, *///%, binary +-, < < = > >, == !=, and, or