CS112 Final

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

Which of the following are str values? Select any/all that apply "hola" 'hello' '''Bonjour''' """pa"""

"hola" 'hello' '''Bonjour''' """pa"""

for i in range(3): for j in range(3): print('*',end=' ')

* * *

for i in range(3): for j in range(3): if j == 1: break print('*',end=' ') print()

** ** **

for i in range(3): if i == 1: break for j in range(3): print('*',end=' ') print()

***

for i in range(3): for j in range(3): if j == 1: continue print('*',end=' ') print()

*** *** ***

LIST METHODS .append(val) .extend(seq) .insert(index,val) .remove(val) .pop.(| index |) .sort() .reverse()

-adds to end -add sequence of values to the end -inserts item at index -removes all instances of val -removes either last itme or item at specified index -sorts list -reverse list

Print -sep=' ' -end= ' ' -\n

-seperation -end of print -new line

i = 1 while i < 5: if i == 1: break print(i) i += 1

0

# of arguments? print( [1,2,3], (4,5,6,7,8), 9, 10)

4

i = 0 while i <= 3: print(i) i += 1

4

seq = ([4,3,2], 5, ("bread", "milk", ["eggs"]), "oranges") seq[1] seq[0][1] seq[-1] len(seq)

5 3 "oranges" 4

x = 0 if x+x == '0': print(x+x) else: if x%9==0: print(x+9, end=".") if x**0.5==3: print(3)

9

Internal methods can not be called; e.g., my_instance._calc() results in an error. T or F

False

Reading a file that doesn't exist will behave like the file exists and is empty. True or false?

False

T or F: When a function call supplies a positional argument for parameter x, and also provides a keyword argument for parameter x, the positional argument is ignored

False

T or F: When we use a raise statement, it must be directly inside a try or except block.

False

T or F: function might return normally with a return value, or an exception object may crash out of it, but it's impossible for both to happen for a single call of the function.

False

T or F: recursive functions' parameters are always aliases of each other, between all the calls that are currently active at any point in time

False

Each call to .write() also writes a new line at the end. True or false?

False Unlike print(), the .write() method does not automatically append a newline to the string argument.

Set items are automatically stored in ascending order. True or false?

False sets do not have an order, just unique values

When the following expressions are evaluated, what will the type of the result be? Note: we are asking for type not result. Assume: x = 3, y = 7, z = 4.0, s = "2". y / x x * z int(y) + int(z) x * s z**int(s) x//y

Float Float int str float int

Complete the statement to create a new instance of Widget with p1=15 and p2=5 class Widget: def __init__(self, p1, p2): # ... widg =

Widget(15, 5)

x = 'George Mason University' y = x.split('e') print(y[0:2])

['G', 'org', 'Mason Univ', 'rsity']

x = [[1, 2, 3], 4, 5, 6, (7.0,)] y = x[::-1] print(y)

[(7.0,), 6, 5, 4, [1, 2, 3]]

x = [1, 2, 3] y = x y.append(0) print(x) del x[0] print(y)

[1,2,3,0] [2,3,0]

print(list(range(2,8,3)))

[2,5]

def mystery(data): data.append(20) data = [30, 40] data[0] = 50 return data x = [0,1,2,3] print(mystery(x),x)

[50, 40] [0, 1, 2, 3, 20]

print(list(range(2,8,-3)))

[]

Which of these are valid identifiers? Select any/all that apply. school-year 3Dpoint ____1 twitter_hashtag_#trending error Se7en_MOVIE_

____1 error Se7en_MOVIE_

A constructor method that defines and initializes instance variable; also called automatically

__init__

Which of the following are legal string expressions? a. "\"Frosty the Snowman!\"" b. 'Let it snow, ' * 3 c. 25 + ' or 6 to 4' d. '''It's cold outside'''

a. "\"Frosty the Snowman!\"" b. 'Let it snow, ' * 3 d. '''It's cold outside'''

What letter(s) print when the following code runs? try: x = 5 xs = [1,3,5] y = xs[x] except Exception as e: print("A") except IndexError as e: print("B") else: print("C") a. A b. B c. AC d. BC e. ABC

a. A

Which of the following things can't be used as a dictionary key? a. {1,2,3} b. "456" c. (7,[8,9],10) d. frozenset( [11,12,13] )

a. {1,2,3} c. (7,[8,9],10)

What does "other" mean in the context of a class method?

allows for comparisons between two objects of the same class (using Boolean operators is called overloading)

What is printed by the following code? def chomp(xs): if xs==[]: return 0 if xs[0]%2==0: return 1 + chomp(xs[1:]) else: return chomp(xs[1:]) print (chomp( [5,6,7,8,9] )) a. 1 b. 2 c. 3 d. 4 e. 5

b. 2

What is printed? def func(xs): for x in xs: if x%2==0: return x print(func( [1,2,3,4,5,6] ) ) a. 1 b. 2 c. 6 d. [2,4,6] e. None

b. 2

After the following code is run, how many lines are in the file named "sample.txt"? f = open("sample.txt", "w") f.write("you") f.write("are\nsmart") f.write("good luck :)") f.close() a. 1 b. 2 c. 3 d. 4 e. 5

b. 2 (you are smart good luck)

How many Point objects are created in the following code? q = Point(1,1) rs = [Point(2,2),Point(3,3)] t = rs[0] u = q v = point(6,6) a. 3 b. 4 c. 5 d. 6 e. 7

b. 4 #U IS JUST AN ALIAS

Given the following import statement: Import math Which of the following print statements succeed? (doesn't crash) a. print(pi) b. print(math.pi) c. print(from math pi) d. print(pi.math)

b. print(math.pi) (THINK OF MATH AS A CLASS AND PI AS A METHOD)

# of arguments? print( "one" + str(1) + won("3") )

1

d = {(0,0):'A', (0,1):'B'} print(d.get(0,1))

1

x = 10 y = x+1 y = 10 print(x)

10

x = 5 y = x*3 x = 10 print(x) print(y)

10 15

Which of the following are int values? Select any/all that apply. 1234123412341234 10 2.0 5.2

1234123412341234 10

i = 0 while i < 4: if i % 2 == 0: print(i) i += 1

2

What is printed? x = y = z = 1 x += z y -= x print(x,y,z)

2 -1 1

nums = set([1,1,2,2,3]) print(len(nums)):

3

How many arguments? print("a",5+5,[3,2]) print(list(range(0,5,2)))

3 1

occurs when a user interacts with an object at a high-level, allowing lower-level internal details to remain hidden (aka information hiding or encapsulation).

Abstraction

What is printed? xs = [1, (2,"two",11), [3,4,5], (6,"seven",8)] print(xs[2][1:][0]) A) 6 B) "seven" C) 4 D) 3 E) 2

C) 4

What is the final value of yss? xs = [] yss = [xs, xs] for i in range(len(yss)): yss[i].append(i) A) [[],[]] B) [[0],[1]] C) [[0,1],[0,1]] D) An exception will be triggered

C) [[0,1],[0,1]]

A template to define common attributes and behavior shared by a group of values

Class

Process of defining how a class should behave for some common operations. Such operations might include printing, accessing attributes, or how instances of that class are compared to each other.

Class customization

methods that a programmer calls to create, modify, or access a class instance.

Class interface

Given: x = True y = False z = False. How many expressions below are evaluated to be True? I) x or y and z → True (and takes precedence over or unless you have () ) II) (not x) == y → True III) not (y and z) → True A) 0 B) 1 C) 2 D) 3

D) 3

def func(a,b): a = a -1 b.append(a) x = 5 y = [8,7,6] func(x,y) print(x,y) A) 4 [8,7,6,5] B) 4 [8,7,6,4] C) 5 [8,7,6,5] D) 5 [8,7,6,4] E) 5 [8,7,6]

D) 5 [8,7,6,4]

What is printed by this code: x = 2 y = 4 x *= y - 1 print(x) A) 3 B) 4 C) 5 D) 6 E) 7

D) 6

Each call to .write() overwrites the previous contents of the file. True or false?

False

given: d = {1:(9,8,7,6), '1':[5,4], 'one':'321'} what do these expressions evaluate to? len(d[0]) d['1'][1] d.get(1.1, 1) d[(9,8,7,6)]

Error - no key called 0 4 1 - since 1.1 is not a key, the default, in this case, 1, was returned Error - no key called (9,8,7,6)

All variables are stored in the global scope of your program, true or false? T or F

False

A function that describes behavior of an object

Method

An attribute that exists in every object to describe its status

Object

A class interface consists of the methods that a programmer should use to modify or access the class T or F

True

A well-designed class separates its interface from its implementation. T or F

True

Internal methods used by the class should start with an underscore in their name. T or F

True

T or F : When a selection statement is of the form if-elif -elif-else, it's possible that either zero or one of the four branches will run.

True

T or F: A dictionary can store two different key-value pairs that have the same value associated with both keys.

True

T or F: In a correct recursive function definition, the base cases must be checked before performing the recursive calculation.

True

T or F: When executing a for loop, the body of code can run as few as zero times.

True

x = [1,2,3,4,5] y = x z = y[:] w = x.copy() id(x) == id(y) id(x) == id(z) id(y) == id(z) id(w) == id(x)

True False False False

Which claim is INCORRECT? a. Opening an existing file for writing overwrites the old file #CREATES NEW FILE b. Opening a non-existent file for reading leads to an error c. Attempting to open a file for appending that doesn't exist leads to an error d. Multiple read/readlines calls advance further into the file each time

c. Attempting to open a file for appending that doesn't exist leads to an error

Given the following function definition, which option can NOT be used to call it? def f(x1,x2,x3,x4): return x1+x2+x3+x4 a. f(1, 2, 3, 4) b. f(x4=4, x3=3, x2=2, x1=1) c. f(x1=1, x2=2, 3, 4) d. f(1, 2, 3, x4=4)

c. f(x1=1, x2=2, 3, 4)

The Question class contains this method: def surprise(self,n): We are given the variable q, which refers to a Question object. Which of the following correctly calls the surprise method? a. surprise(5) b. surprise(q, 5) c. q.surprise(5) d. Question.surprise(5)

c. q.surprise(5)

What is printed by the following code? a = {1,2,5,7} b = {2,4,5,8} # & = ADDS, | TAKES SIMILAR ONES, ^ DIFFER c = {1,3,5} # - IS THE DIFFERENCE VALS OF BOTH print(sorted(a-(b&c))) a. {} b. {7} c. {1,2,7} d. {1,2,5,7} e. {3,4,8}

c. {1,2,7}

my_str = 'The cat in the hat' print(my_str[3:7])

cat (needs a space)

attribute shared amongst all of the instances of that class.

class attribute

What is __init__ also called?

constructor

Consider the file below. What is printed by the following code? Letters.txt ABCDEFG 1234567 abcdefg f = open("letters.txt", "r") s1 = f.read(2) s2 = f.read(3) #S2 STARTS OFF S1, SO IT'S THREE CHARS AFTER 2 print(s2) a. ABC b. C c. E d. CDE e. abcdefg

d. CDE

Given two sets s1 and s2, which of the following is correct? a. s1<s2 is True if len(s1)<len(s2) #EX: s1 = {1,2,3}, s2= {1,2,3,4} b. s1<s2 is True if min(s1)<min(s2) #S2 HOLDS ALL THE VALS OF S1 & MORE c. s1<s2 is True if max(s1)<max(s2) d. s1<s2 is True if s1 is a proper subset of s2 e. s1<s2 is an illegal operation

d. s1<s2 is True if s1 is a proper subset of s2

Create a function, delete_elements, that removes from the list xs the first, middle, and last item. Do not use return. Do not create a new list (modify in-place). You can assume xs contains an odd number of elements and more than 4 elements. def delete_elements(xs):

def delete_elements(xs): half = int(len(xs)/2) xs.pop(half-1) xs.pop xs.pop(0)

Which of the following are not valid ways to define functions? Select any/all that apply. def func(a=b, b=c, c=0): #code goes here def func(a, b, c, c=0): #code goes here def func(d, c, b=2, a=1): #code goes here def func(a, b=0, c): #code goes here

def func(a, b, c, c=0): #code goes here def func(a=b, b=c, c=0): #code goes here def func(a, b=0, c): #code goes here

Complete the function that returns the sum of only the negative elements of num_list def sum_negative(num_list):

def sum_negative(num_list): sum = 0 for i in num_list: if i < 0: sum = sum + i return sum

Write a function that prints the values from 5 down to 1 (inclusive, in that order) using a loop. def print5to1():

i = 5 for i in range(5,0,-1): print(i) output : 5 4 3 2 1

attribute unique to each instance

instance attribute

A single instance based on a template

instance variable

calling the class using parentheses ex: my_time = Time()

instantiation

given a file with: line one second the third line five What is the output if this code? f = open("example.txt") print( f.readline() ) print( f.readline() )

line one second

what does the .split(x) command do? -divides the word evenly -splits up string with val x into one letter tuple (splits when the code gets to val x) -makes a list of split up words excluding val x (splits when the code gets to val x)

makes a list of split up words excluding val x (splits when the code gets to val x)

Definition in a class

method

Add a single print statement that will print both x and y on consecutive lines. x = 100 y = 200 #your printing code is next!

print(str(x)+"\n"+str(y))

for __str__ definitions, what format should you use?

return ('{}, {}'.format(x,y))

Given the following file (example.txt): line one second the third line five What does this code print: Given the following file (example.txt): line one second the third line five what does the following code print? f = open("example.txt") f.read(4) f.read(5) s = f.read(2) print(s)

se

A method parameter that refers to the class instance.

self

A method parameter that refers to the instance this method is called for

self

given def __init__(self, start_hrs, start_mins, end_hrs, end_mins, dist):

self.start_hrs = start_hrs self.start_mins = start_mins self.end_hrs = end_hrs self.end_mins = end_mins self.distance = dist

seq = ([4,3,2], 5, ("bread", "milk", ["eggs"]), "oranges") what is seq[2] what is seq[0][1:]

tuple list

immutable

unchangeable

IF: b = true x = 7 y = 2 s1 = '5' s2 = 'five' s3 = 'FIVE' Which of the following evaluates to True? x < 5 or y > 5 x - y == x - y (not b) or b or False not (b and not b) b and s2 != s3 (y**2) + 1 == int(s1) not ((not b) or (x > y)) and s3 == '5' s1 + s1 + s1 + s1 + s1 == (x - y) * 5

x - y == x - y (not b) or b or False not (b and not b) b and s2 != s3 (y**2) + 1 == int(s1)

Fill in the empty line with a python command so that the output is 3.0 x = 3 x *= 2+3 #your code on this line! print((y%x)/3)

y = 24

Predict the output d = {} for i in range(-2,2,1): d[2] = i print(d)

{2: 1} because range goes: -2 -1 0 1 STOPS so last value is 1


Kaugnay na mga set ng pag-aaral

APES chapter 5 biodiversity, species interactions and population control

View Set

Test 1 - Part II - Structure of the Bacterial Cell: Periplasm, Peptidoglycan, Gram Positive Cell Wall, and Gram Negative Cell Walls

View Set

Chapter 3 and 4 quiz Video Production

View Set

Types of Life Insurance Policies

View Set

The cavities and chambers of the eye

View Set

BUS-538 Identity and Access Management

View Set

Ch.1 - An introduction to relational databases and SQL

View Set

The Congress of Vienna and Nationalism

View Set