Exam 1

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

What will the following code display? myset = set('1 2 3 4') print(len(myset))

5

A(n) _______________________ sometimes called an ADT, is a logical description of how we view the data and the operations that are allowed without regard to how they will be implemented. A dictionary is an example of an ADT

Abstract Data Type

____________ is the study of problems that are and are not computable. It is also the study of abstraction

Computer Science

What will be the output after the following code is executed and the user enters -35 and 0 at the first two prompts? def main(): try: total = int(input("Enter total cost of items? ")) num_items = int(input('Number of items ")) average = total / num_times except ValueError: print('Error: cost cannot be negative') except ValueError: print('Error: number of items cannot be negative') except ZeroDivisionError: print('Error: cannot have 0 items')

ERROR: cannot have 0 items

A subclass may not override any method other than the __init__ method

False

The elements in a dictionary are stored in ascending order, by the keys of the key-value pairs

False

What is output? def divide_by_two(count): if count == 1: print('Terminated...!') else: print(count) divide_by_two(9)

Infinite Loop

What is the output? def water_temperature_for_coffee(temp): if temp <195: print('Too cold') elif (temp >= 195) and (temp <= 205): print('Perfect temperature.') elif (temp > 205): print('Too hot') water_temperature_for_coffee(205) water_temperature_for_coffee(190)

Perfect temperature Too cold

Each subclass has a method named __init__ that overrides the superclass's __init__ method

True

What is output? dict = {1: 'X', 2: 'Y', 3: 'Z'} print(dict.get(2, 'A'))

Y

What is the value of new_list? my_list = [['hey', 'hello', 'hi'], 'good morning'] new_list = [i+'!' for i in my_list[0]]

['hey!', 'hello!', 'hi!']

What is output? new_list = [10, 'ABC', '123', 25] my_list = new_list[:] new_list[2] = 16 print(new_list) print(my_list)

[10, 'ABC', 16, 25] [10, 'ABC', '123', 25]

Which method is automatically executed when an instance of a class is created in memory?

__init__

Select the option to get the value of temperature from the dictionary my_dict = {'County': 'India', 'State': {'City': 'Delhi', 'Temperature': 40}}

my_dict['State']['Temperature']

Given the following class definition, which of the following is the correct call for the method? class Games: def __init__(self: self.fav__game = 'Tennis' def print_game(self, diff_game): print('{0} is a better game than {1}.'.format(self.fav_game, diff_game))

my_game = Games() my_game.print_game('Rugby')

Write a statement that creates a dictionary, called mydict, containing the following key-value pairs: 'a': 1 'b': 2 'c': 3

mydict = {'a': 1, 'b': 2, 'c': 3}

Which would be the base case in a recursive solution to the problem of finding the factorial of a number. Recall that the factorial of a non-negative whole number is defined as n! where: if n = 0, then n! = 1 if n > 0, then n! = 1 x 2 x 3 x... x n

n = 0

Recursion is

never required to solve a problem

A recursive function includes ________________ which are not necessary in a loop structure.

overhead actions

Which method would you use to get the value associated with a specific key and remove that key-value pair from the dictionary?

pop

Complete the code to get a factorial of a number. def factorial(number): if number == 0: return1 else: XXX print(factorial(4))

return number*factorial(number-1)

Which condition is the recursive case for sum of the first n natural numbers? def nsum(n): if n==0: sum =0 elif n==1: sum = 1 else: sum = n + nsum(n-1) return sum

sum = n + nsum(n-1)

Which of the following is an attribute of the class shown below? class Student: def __init__(self): self.age=0 self.height=0 self.weight=0

weight

What is the value of rgb_a? colors = {1: 'red', 2: 'green', 3: 'blue', 4: 'yellow'} popped_item = colors.pop(4) colors_update({4: 'alpha'}) rgb_a = {} rgb_a['items'] = colors

{'items': {1: 'red', 2: 'green', 3: 'blue', 4: 'alpha'}}

Consider the following sessions: In [1]: numbers = list(range(10)) + list(range(5)) In [2]: numbers Out [2]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4] In [3]: set(numbers) Out [3]: ???

{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

What is the relationship called in which one object is a specialized version of another object?

is a

Which XXX/ZZZ outputs every name/grade pair in the dictionary, as in: Jennifer: A? grades = { 'Jennider': 'A', 'Ximin': 'C', 'Julio': 'B', 'Jason': 'C' } for XXX: print(ZZZ)

name in grades / name + ':' + grades[name]

What would be the output of the following code? primes = { 3, 5, 7, 11, 13, 17, 19, 23, 29} teens = set([13, 14, 15, 16, 17, 18, 19]) print(primes - teens)

{3, 5, 7, 11, 23, 29}

Suppose you have an algorithm that tests whether any element of an array is duplicated elsewhere in the array. The first element must be compared with all the other array elements. The second element must be compared with all the other array elements except the first (it was already compared to the first). The third element must be compared with all the other array elements except the first two. In the end, this algorithm makes. (n-1) + (n-2) + ... + 2 + 1 or n^2/2-n/2 comparisons. Which of the following statements is flase? a. As n increases, the n^2 term dominates, and the n term becomes inconsequential. O(n^2) notation highlights the n^2 term, ignoring n/2. O(n^2) is referred to as quadratic run time and pronounced "on the order of n squared' or more simply "order n-squared" b. Big ) is concerned with how an algorithm's run time and grows in relation to the number of itmes, n, processed. When n is small, O(n^2) algorithms (on today's super-fast computers) will not noticeably affect performance, but as n grows you'll start to notice performance degradation. c. An O(n^2) algorithm operating on a billion-element array (not unusual in today's big-data applications) would require a quintillion operations, which on today's desktop computers all the other array elements could take approximately 13.3 years to complete! O(n^2) algorithms, unfortunately, are easy to write D. All the above statements are true

D. All the above statements are true

What gives a program the ability to call the correct method depending on the type of object that is used to call it?

Polymorphism

What does the acronym UML stand for?

Unified Modeling Language

When an object is passed as an argument, _______________________ is passed into the parameter variable

a reference to the object

Which of the following cab though of as a self-contained unit that consists of data attributes and the methods that operate on the data attributes?

an object

A base case is recursion is a __________________

case that returns a value without performing a recursive call

Look at the following class definition: class Mammal: def __init__(self, name): self.__name = name Write the code for a class named Bear that is a subclass of the Mammal class. The Bear class's __init__ method should call the Mammal class's __init__ method, passing 'Bear' as an argument

class Bear(Mammal): def __init__(self): Mammal.__init__(self, 'bear')

Write a class definition named Car. The Car class should have data a attribute for a Car's make. The class should also have the following: a. An __init__ method for the class. The method should accept an argument for each of the data attributes b. Accessor and mutator methods for the make attribute c. __str__ method that returns a string indicating the state of the object

class Car: def __init__(self, make): self.__make = make def set_make(self, make): self.__make = make def get_make(self): return self.__make def __str__(self): state_string = ('make: ' + self.__make + '\n') return state_string

Which is an example of inheritance?

class Elements: def __init__(self): self.name = '' class Metal(Elements): def __init__(self): Elements.__init__(self) self.mass = '' self.atomicNumber = '' class NonMetal(Elements): def __init__(self): Elements.__init__(self) self.mass = '' self.atomicNumber = ''

Which of the following statements is false? a. All classes inherit from object directly or indirectly, so they all inherit the default methods for obtaining string representations that print can display b. Python also has duck typing, which the Python documentation describes as: A programming style which does not look at an object's type to determine if it has the right interface; instead, the method or attribute is simply called or used ("If it looks like a duck and quacks like a duck, it much be a duck.") c. When Python processes an object at execution time, its type does not matter. As long as the object has the data attribute, property or method (with the appropriate parameters) you wish to access, the code will work. d. All of the above statements are true

d. All of the above statements are true

Suppose an algorithm is designed to test whether the first element of an array is equal to the second. If the array has 10 elements, this algorithm requires one comparison. If the array has 1000 elements, it still requires only one comparison, Which of the following statements is false? a. The algorithm is completely independent of the number of elements in the array. b. This algorithm is said to have a constant run time, which is represented in Bid O notation as O(1) and pronounced as "order one" c. An algorithm that's O(1) does not necessarily require only one comparison. O(1) simply means that the number of comparisons is constant--it does not grow as the size of the array increases. d. An algorithm that tests whether the first element of an array is equal to any of the next three elements is O(3)

d. An algorithm that tests whether the first element of an array is equal to any of the next three elements is O(3)

Which of the following statements is false? a. Python provides two built-in functions --issubclass and isinstance-- for testing "is a" relationships. b. Function issubclass determines whether one class inherits from another c. Function isinstance determines whether an object has an "is a" relationship with a specific type. d. If SalariedCommissionEmployee inherits from CommissionEmployee, and if object s is aSalariedCommissionEmployee, then the following snippet results are correct: In [19]: isinstance(s, CommissionEmployee) Out [19]: False In [20]: isinstance(s, SalariedCommissionEmployee) Out[20] True

d. If SalariedCommissionEmployee inherits from CommissionEmployee, and if object s is aSalariedCommissionEmployee, then the following snippet results are correct: In [19]: isinstance(s, CommissionEmployee) Out [19]: False In [20]: isinstance(s, SalariedCommissionEmployee) Out[20] True

Which of the following statements is false? a. Both iteration and recursion are based on a control statement: Iteration uses an iteration statement (e.g., for or while), whereas recursion uses a selection statement (e.g., if or if ... else or if... elif ... else). b. Iteration and recursion each involve a termination test: Iteration terminates when the loop-continuation condition fails, whereas recursion terminates when a base case is reached. c. Iteration with counter-controlled iteration and recursion both gradually approach termination: Counter-controlled iteration keeps modifying a counter until the counter assumes a value that makes the loop-continuation condition fail, whereas recursion keeps producing smaller versions of the original problem until the base case is reached d. Only iteration can occur infinitely: An infinite loop occurs with iteration if the loop-continuation test never becomes false

d. Only iteration can occur infinitely: An infinite loop occurs with iteration if the loop-continuation test never becomes false

Comlete the code to generate the following output: Inside the child class class ParentClass: def action(self): print('Method is not overridden') class ChildClass(ParentClass): def action(self): print('Inside the child class') if __name__ == '__main__' XXX

d. r.action()

The following function uses a loop. Rewrite it as a recursive function that performs the same operation. def traffic_sign(n): while n>0: print('No Parking') n = n - 1

def traffic_sign(n): if n>0: print('No Parking') n = n - 1

Which of the following code blocks will print both keys and values?

dict1 = dict(number = 10, color = 'Red', word = 'Chair') for keys, values in dict1.items(): print(keys, values)

In the code below, identify the correct instantiation of a new class object. class Subtract: def__init__(self, num1, num2): self.num1= num1 self.num2= num2 def calculate_diff(self): diff= self.num1 - self.num2 print(diff)

diff1 = Subtract(25, 10)

Which of the following is an instance created by the code given below? class Employee: self.id = 0 self.name = 'ABC' self.title = 'Business Analyst' employee1=Employee() employee1.id = 122654 print('{} {} {}'.format(employrr1.id, employee1.name, employee1.title))

employee1

In order to avoid KeyError exceptions, you can check whether a key is in the dictionary using the _____________ operator

in

______________ is a concept where the derived class acquires the attributes of its base class.

inheritance

Complete the code to generate the following output: 16 18 class Rect(): def__init__(self.length, breadth) self.length = length self.breadth = breadth def getArea(self): print(self.length * self.breadth) class Sqr(Rect): def__init__(self, side): self.side=side Rect__init__(self, side, side) def getArea(self): print(self.side*self.side) if __name__ == '__main__' xxx

square = Sqr(4) rectangle = Rect(2,4) square.getArea() rectangle.getArea()


Set pelajaran terkait

Intro to Marketing HW #5 questions

View Set

pharm prepu 29: Drug Therapy for Shock and Hypotension

View Set

IS-0700.b An Introduction to the National Incident Management System

View Set

Sensory Receptors Connect Assignment

View Set