CS 211 Study guide from mini exams

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

What is the output of the following Python program? def myfunction(n): if n == 0: return n else: return myfunction(n-1) myfunction(10) a) None b) 55 c) 0 d) 10

0

What will be the output of the following Python code? class SuperClass: def __init__(self): self.x = 0 class SubClass(SuperClass): def __init__(self): self.y = 1 b = SubClass() print(b.x,b.y) a) 0 1 b) Error: SubClass object has no attribute x c) 1 0 d) 0 0

0 1

What is the output of the following program excerpt? a = 0b10111011 bitmask = 0b100 print(bin(a | bitmask)) 0b10111111 0b00000011 0b100 Syntax Error

0b10111111

What is the output of the following code snippet? class Add: def __init__(self, x, y, z): self.sum = x+y+z x = Add(1, 2, 3) y = x.sum x.sum = y + 1 print(x.sum) A) 6 B) <__main__.Add object at 0x1043645e0> C) 7 D) None

7

What is a class

A class acts as a blueprint for objects. It defines the attributes (parameters/data) and behaviors(methods/functions)

what is a concrete class?

A concrete class is a regular class that is not an abstract, and can be instatiated. It has it owns attributes, and implementation of the methods defined in the abstract class.

What is a constructor

A constructor is a way to initialize the objects attributes, and set their values

What is a recursive object

A recursive object is an object that contains references to other objects of the same type, either directly or indirectly

What is the output of the following code snippet?class A: def m1(self): return self.m2() def m2(self): return 'A' class B(A): def m2(self): return 'B' a = A() b = B() print(a.m1(), b.m1(),a.m2(), b.m2()) A) A B A A B) A B A B C) A A A B D) A B B A

A) A B A A

What does the __init__(self) method do inPython? A) It initializes the class for use. B) It executes when a new object is instantiated. C) It initializes all the data attributes to zero when called. D) It sets self to None

A) It initializes the class for use.

What statement is false about the following execution sequence? >>> a[1, 2, 3] >>> type(a) <class 'list'> >>> a.pop() 3 >>> a [1, 2] A) pop is an in-place method B) pop deletes and returns the last list element C) [].pop() returns [] D) Lists are mutable objects

A) pop is an in-place method

Aliasing in python

Aliasing in programming refers to the situation where two or more variables refer to the same object or memory location in the computer's memory. This means that if one variable is changed, the other variable(s) that refer to the same location will also be affected.

What are dunder methods

Also known as magic methods. Is used to define built in behaviors such as str, and + operator of a particular class

What is an object

An object is an instance of a class that has its own values, and attributes

What is an abstract class? A) An abstract class is one without any child classes. B) An abstract class is any parent class with more than one child class. C) An abstract class is a class that cannot be instantiated but can be a base class. D) abstract class is another name for "baseclass.

C) An abstract class is a class that cannot be instantiated but can be a base class.

Which of the following code uses the inheritance feature of Python? A) class Foo: Pass B) class Foo(object): pass class Bar(object): pass C) class Foo: pass class Bar(Foo): pass D) None of the above

C) class Foo: pass class Bar(Foo): pass

What built-in list method would you use toremove items from a list? A) .delete() method B) pop(my_list) C) del(my_list) D) .pop() method

D) .pop() method

Can an abstract parent class have non-abstract subclasses? A) No—an abstract class must have only abstract subclasses. B) No—an abstract class must have no subclasses at all. C) Yes—all children of an abstract class must be non-abstract .D) Yes—an abstract class can have both abstract and non-abstract subclasses.

D) Yes—an abstract class can have both abstract and non-abstract subclasses.

Factoring functionality in class hierarchies

Factoring functionality in class hierarchies refers to the process of extracting common functionality from related classes and moving it to a base class to reduce code duplication and improve maintainability.

Consider the following program snippet class Scoop(): def __init__(self, flavor): self.flavor = flavor... class IceCream(): def __init__(self, flavors): self.scoops = [Scoop(x) for x in flavors] Which of the following statements is true? a) Scoop contains IceCream b) IcdCream is Scoop c) IcreCream contains Scoops d) Scoop is IceCream

IceCream contains Scoops

Consider the class class IceCreamCone: def __init__(self, flavor, size): self.flavor = flavor self.size = size What is the correct form to instantiate the above Scoop class and create an object? a) IceCreamCone.create("vanilla", "small") b) IceCreamCone("vanilla", "small") c) IceCreamCone.__init__("vanilla", "small") d) IceCreamCone.instantiate("vanilla", "small")

IceCreamCone("vanilla", "small")

What is inheritance in object oriented programming

Inheritance is a powerful feature of object-oriented programming that allows one class to inherit the properties (methods and attributes) of another class.

What is the output of the following code? class Foo: def printLine(self, line='Python'): print(line) o1 = Foo() o1.printLine('Java') a) Java b) Python c) Line d) Nothing, it raises a syntax error exception..

Java

what is method overriding

Method overriding is a feature of object-oriented programming that allows a subclass or child class to provide a specific implementation of a method that is already defined in its parent or superclass. When a method is called on an object of the child class, the implementation in the child class will be used instead of the implementation in the parent class. This allows the child class to modify the behavior of the inherited method in a way that is appropriate for its own needs.

Assuming the methods add and str are correct, what will the following program snippet print? class Point: ... def __add__(self, d): ... def __str__(self, d): ... p1 = Point(3, 5) p2 = Point(10, 12) print(p1+p2) a) (13, 17) b) <__main__.Point object at 0x104573c70> c) Nothing - Syntax error

Nothing - syntax error

In the following code snippet (studied in class) class Rect:. .. def area(self): ... class Square(Rect): ... def area(self): ... What can we say about the area method? a) Square.area overrides the inherited Rect.area method b) You cannot redefine inherited methods c) Square.area and Rect.area are non-related methods d) Square.area is inherited from Rect.area

Square.area overrides the inherited Rect.area method

What do you call a class that inherits attributes and methods from another class? Inheritance Polymorphism Superclass Subclass

Subclass

What is an abstract class?

They are used to declare common characteristics of subclasses. An abstract class cannot be instantiated, only extended. Abstract classes are declared with the "abstract" keyword. Can have both implemented and abstract methods.

Which of the following is a user-generated data structure in Python? List Tuple Tree Array

Tree

An in-place method directly changes the content of the self object without making and returning a copy. a) True b) False

True

Is the expression instruction a valid Python condition? 'a'<=char<='z' True or False

True

Is the following conditional expression c=='a' or c=='e' or c=='i' or c=='o' or c=='u' equivalent to this second one? c in "aeiou" True or False

True

Polymorphism is an Object Oriented Programming feature. True or False

True

When superclass A inherits to subclasses B and C, and there is repeated code in B and C, we can factor the duplicated code, eliminate it from B and C, and send it to class A. That way, the same code is inherited by B and C. True or False

True

Which of the following data structures in Python are immutable? Linked List Tuple Tree Dictionary

Tuple

What is the output of the following program excerpt? org = 'QuizArbit' org[4] = 'O' org = list(org) if len(org) == len('QuizOrbit'): print('Best Quiz Platform') else: print('Exiting!') a)Best Quiz Platform b)Exiting c)TypeError: 'str' object does not support item assignment d)Syntax Error

TypeError: 'str' object does not support item assignment

The following program flattens a list (parameter my_list) whose depth is at most two. a_list may have a depth of one (i.e., [1, 2, 3]) or two (i.e., [1, [2, 3], [4, 5]]). def flatten(a_list): """non-rec flatten for nested lists of depth 2""" flatlist = # complete this line return flatlist Select the correct expression for the assignment instruction. a) [flatten(element) for element in a_list] b) [element for sublist in a_list for element in sublist] c) d) [element for element in a_list]

[flatten(element) for element in a_list]

In the following function 1 def pack(x, y): 2 mask = 0xF 3 left = x & mask # bitwise and 4 right = y & mask # bitwise and 5 left = left<<4 6 result = left | right 7 return result What is line 5 doing? a) Shifting the bits in variable left 4 positions to the left b) Left justifying the number 4 c) Syntax error d) Setting the 4 leftmost digits of the variable left to its previous contents.

a

What is the output of the following code snippet? class A: def test(self): print("A.test") class B(A): def test(self): print("B.test") super().test() a_B = B() a_B.test() a) B.test A.test b) A.test B.test c) A.test d) B.test

a

what is __ format __

a format is the same as __str__ but it takes in arguments, and return varies because of it.

In Python, a class is __________ to create objects. a) an instance b) a distraction c) d) a mold

a mold

In the following program excerpt, Tree is a class containing a list of children, all of which must be Trees (children may be empty.) class Tree: def __init__(self, label, children=[]): self.label = label for ch in children: assert isinstance(ch, Tree) self.children = children We can call a Tree object: a) a representation b) an impossible object c) a recursive object

a recursive object

The following function determines whether or not a string is a palindrome. def palindrome(a_string): if len(a_string) <= 1: return True else: return a_string[0] == a_string[-1] and palindrome(_______________) a_string[1:-1] a_string[1:] a_string[:-1] a_string[:]

a_string[1:-1]

If you want to implement a Stack class, what is the missing (blank) method, assuming you push and pop at the end of the hosting array? class Stack(): def __init__(self): self.s=[] def push(self, data): self.s.__________(data) a) insert b) append c) concat d) add

append

A polynomial can be represented as a list of coefficients. For instance, 1 + 2 x + 3x^2 can be represented by the list [1, 2, 3]. Such a polynomial can be seen as a function of x, f(x) = 1 + 2 x + 3 x^2. The following code fragment defines a class Polynomial. Once a Polynomial object is created, its method eval evaluates the polynomial it represents, given x. Which of the options below corresponds to the missing (underlined blank) expression? class Polynomial: def __init__(self, coefficients: list): self.coef = coefficients self.degree = len(self.coef)-1 def __str__(self): return f"Poly[{self.degree}]: {self.coef})" def eval(self, x: float)->float: result = 0 for i in range(len(self.coef)): result = result + __________ return result Here's an example of the creation and evaluation of a polynomial object. >>>parabola = Polynomial([1, 2, 3]) >>>print(parabola.eval(x=2)) 17 a) x * self.coef[i]**i b) self.coef[i] * x**i c) coef[i] * x**i d) x * coef[i]**i

b

The function below flattens a list. Here is an example of its execution producing the following result: >>>flatten([1, 2, [[[3, [4,5]]]]])[1, 2, 3, 4, 5] Which of the options below corresponds to the missing (underlined blank) expression? def flatten(x: list)->list: if not x: return x if isinstance(x[0], list): return flatten(x[0]) + flatten(x[1:]) else: return _________ + flatten(x[1:]) a) [] b) [x[0]] c) x d) x[0]

b

Which of the following statements are true of inheritance in OOP? a) Programs based on inheritance are harder to debug b) The resulting classes are easier to maintain c) Designing classes based on inheritance is harder d) Designing classes based on inheritance takes longer e) It supports the concept of reusability f) It is transitive - e.g., if class C inherits from class B, which inherits from A, automatically C inherit from class A g) It represents real-world relationships well

b, e, f, g

Consider a class Point defined as follows. class Point: def __init__(self, x, y): self.x = x self.y = y def displace(self, d): x = self.x + d.x y = self.y + d.y return Point(x,y) ... p = Point(1, 2) delta = Point(3, 3) p.displace(delta) print(p) Assume the class Point contains a proper __str__ method. What does the print statement produce? a) (3, 6) b) (4, 5) c) (1, 2)

c

If we represent points as couples, what will the print instruction produce? p1 = (3, 4) p2 = (1, 2) print(p1+p2) a) (4, 6) b) Syntax error, the operator + is not defined for tuples c) (3, 4, 1, 2)

c

What is the correct form to declare that the classDog inherits from Canine? A) from Canine import Dog B) class Dog(Canine) C) an = Dog(Canine) D) Dog = Canine()

class Dog(Canine)

Which of the following instructions shows the correct statement for the Dog class to inherit from the Canine class? a) class Dog(Canine): b) from Canine import class Canine c) an = Dog() d) Dog = Canine()

class Dog(Canine):

The following program counts the number of consonants in a string. What is the correct missing (blank) expression in the last line? def is_consonant(char): char = char.lower() return 1 if char not in "aeiou" and 'a'<=char<='z' else 0 def consonants_rec(a_string): if a_string == "": return 0 else: is_consonant(a_string[0]) + ________________ consonants_rec(a_string[1:]) consonants_rec(a_string[1:]-1) consonants_rec(a_string) a_string[1:].consonants_rec()

consonants_rec(a_string[1:])

In the following code snippet (studied in class) class Point:... def move_to(self, new_x, new_y): self.x = new_x self.y = new_y... What do we call the move_to method? a) overriden b) in_place c) inherited d) external

in_place

What is dynamic method dispatch

is a feature in Python (and many other object-oriented programming languages) that allows a method to be called on an object without knowing the exact type of the object at compile time.

A recursive function is a function that calls __________ during its execution. a superclass itself an auxillary function a subclass

itself

A(n) __________ represents an entity in the real world with its identity and behavior. operator object method class

object

The fact that the operator + works with strings, integers, and lists is known as none of the above data coercion polymorphism

polymorphism

If you want to implement a Stack class, what is the missing (blank) method, assuming you push and pop at the end of the hosting array? class Stack(): def __init__(self): self.s=[] def pop(self): self.s.__________() a) pop b) delete c) remove d) none of the other answers is correct

pop

What is tree walks in python ?

refers to the process of how nodes in a tree data structure are visited

By convention, _________ is used to refer to the current instance (aka, calling object) of a class. A) class B) def C) self D) init

self

What is self for?

self refers to the instance of the class that is currently being manipulated or accessed. It is a way for an instance of a class to refer to itself and its own data and behavior. It is used to access instance variables and methods within the class.

B is a subclass of A. How do you execute A's constructor method from B? select which ones are correct: super().__init__() B.__init__(self) A.__init__(self) super().__init__(self)

super().__init__() A.__init__(self)

Polymorphism

the ability of different objects to be used interchangebly, as long as they have the same base class,

what is a __ str__

this method converts to a string representation for display purposes

what is a __repr__

this method is also converted to str, but has to have the ability to recreate an object

Assume the file lib.py contains class A, whose constructor does not take any arguments. If the file client.py imports lib.py using the form import lib How would you create object x of class A? A) x = A() B) x = lib.A() C) x = A.lib() D) x = lib()

x = lib.A()

What does the last statement print? x = [1, 2, 3] x.append([4, 5, 6]) print(len(x)) A) 6 B) 4 C) Error, cannot append a list to a list

B) 4

What of the following statements about the following code snippet is false? def fun(name): print(f"Hello {name}") cheer = fun cheer('Geeks') A) It prints "Hello Geeks" B) The function cheer is undefined C) cheer and fun are aliases of the same function

B) The function cheer is undefined

What is the term to describe this code? a, b, c = (2, 'apple', 3.5) A) Tuple processing B) Tuple unpacking C) Tuple matching D) Syntax Erro

B) Tuple unpacking

What is the output of the following code snippet? a=1 b=0 index=7 a_list = [1,2,3] try: c=a/b print(a_list[index]) except IndexError as e: print("index out of range") except ZeroDivisionError as z: print("b is 0") A) division by zero B) b is 0 C) list index out of range D) None of above

B) b is 0

Which of the following is the correct way to define a constructor? A) def __init__(title, author): B) def __init__(self, title, author): C) def __init__(): D) __init__(self, title, author):

B) def __init__(self, title, author):

What happens if you do not explicitly return a value from a function? A) It will raise a RuntimeError if you do not return a value. B) It will return None. C) It will return True. D) The function will enter an infinite loop because it will not know when to stop executing its code.

B) it will return None

What built-in Python data type do programmers commonly use to represent a stack? A) set B) list C) None D) dictionary E) You must implement a stack as a class

B) list


संबंधित स्टडी सेट्स

exam 3 questions class, ati, nursing.com

View Set

Understanding Culture, Society, and Politics

View Set

Matthew Desmond's Evicted: Part Three

View Set

Energi - konsekvenser af produktion og forbrug

View Set

Pediatric Growth and Development Quiz 2

View Set