Computer Science 101

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

You cannot write in a lambda function as an argument to another function? True or False?

False

You need a comma and parentheses to create a tuple. True or False?

False

You will get an error when you try to write to a file that doesn't exist. True or False?

False

Data that can be change in place is known as... mutable

Mutable

Overriding

Occurs simply by defining in the child class a method with the same name of a method in the parent class.

"hello world 2021"[::-1] What is the output?

Output = 1202 dlrow olleh

"hello world 2021"[-2:2:-1] What is the output?

Output = 202 dlrow ol

difference()

Returns the difference of two or more sets as a new set.

intersection()

Returns the intersection of two sets as a new set.

symmetric_difference()

Returns the symmetric difference of two sets as a new set.

union()

Returns the union of sets in a new set.

issubset()

Returns true if another set contains this set.

issuperset()

Returns true if this set contains another set.

isdisjoint()

Returns true if two sets have a null intersection.

A function inside of a class is also known as a method. True or False?

True

A tuple contains an unordered collection of unique and immutable objects. True or False?

True

An expression returns a value. True or False?

True

Constructors are not necessary for classes. True or False?

True

Dictionary values must be mutable. True or False?

True

Else blocks run when the Boolean expression of the if statement is false. True or False?

True

If you don't specify an error to an except block, it will catch all errors. True or False?

True

If you don't specify an error with an except block, then it will catch all errors. True or False?

True

Overriding a parent class' method in a derived class is known as Polymorphism. True or False?

True

Strings can be created by using a string comprehension. True or False?

True

Tuples, lists, and strings are all similar with how indexing and slicing works. True or False?

True

You are unable to output to files using the print() function. True or False?

True

You don't need parentheses () to create a tuple, just a comma. True or False?

True

symmetric difference_update()

Updates a set with the symmeteric difference of itself and another.

intersection_update()

Updates the set with the intersection of itself and another.

update()

Updates the set with the union of itself and others.

__________ is used to create an object. a. Class b. Constructor c. User_defined functions d. In-built functions

b. Constructor

Why do classes need constructors? a. They don't. b. They're used to initialize the instance attributes for that instance of the class. c. Constructors are important because they will check to make sure all of your methods aren't throwing any errors. d. The constructor will tell the program where each variable is saved in the memory.

b. They're used to initialize the instance attributes for that instance of the class.

Which of the following functions overloads the * operator? a. __mult__(self,other) b. __mul__(self, other) c. __multiply__(self, other) d. __times__(self, other)

b. __mul__(self, other)

Which of the following is a correct way to open a text file for reading? a. file = open"text_file.txt" b. file = read("text_file.txt", "r") c. file = "text_file.txt" d. file = open("text_file.txt")

b. file = read("text_file.txt","r")

To read the entire remaining contents of the file as a string from a file object infile, we use... a. infile.read(2) b. infile.read() c. infile.readline() d. infile.readlines()

b. infile.read()

What is recursion? a. When a function gets called inside of a loop. b. When a function calls another function (once). c. A loop inside of a loop. d. A function calling itself over and over.

d. A function calling itself over and over.

The else statement can be used with: a. if b. while c. try except d. All of the above

d. All of the above

Which of the following statements is false about recursion? a. Every recursive function must have a base case. b. Infinite recursion can occur if the base case isn't properly mentioned. c. A recursive function makes the code easier to understand. d. Every recursive function must have a return value.

d. Every recursive function must have a return value

Which of the following does not create a tuple? a. myTuple = (1,2) b. myTuple = (1,) c. myTuple = 1,2 d. myTuple = (1)

d. myTuple = (1)

'a'

for appending

'w'

for writing

Describe the three methods used for reading files (text files).

read() - Returns the read bytes in form of a string readline() - Reads a line of the file and returns in form of a string readlines() - Reads all the lines and return them as each line in a string element in a list

'r'

read-only

'r+'

reading and writing

A variable passed to function is known as a... argument

Argument

Except

A block of code that is associated with the try block. Will run when the specified exception is thrown, or if no exception is specified, then it will run when any exception is thrown.

A+

A file mode that, if the files exist, then the file contents are left intact and reading and writing begins at the end of the file. If the file does not exist, it creates and opens a new file.

What is recursion?

A function calling itself over and over.

Sorted()

A function that returns a sorted list of the specified iterable object. You can specify the ascending or descending order. Strings are sorted alphabetically, and numbers are sorted numerically.

Recursion

A type of function that takes one basic task and divides it into multiple subtasks by calling itself over and over.

Tuple

A type of sequence/collection in which all elements are ordered and it is immutable.

Set

A type of sequence/collection in which all elements are unordered and unique

append()

Adds an element at the end of the list.

add()

Adds an element to the set.

Procedure

Allows us to group a block of code under a name, known as a procedure name. We can then call the block of code from anywhere in the program to execute the instructions it contains. We can also pass values to the procedure to change how it works.

Lambda

An anonymous function with a specific keyword and syntax arguments: expression

What is the module used to read/write CSV files?

CSV

Why do classes need constructors?

Constructors are generally used for instantiating an object. The task of constructors is to initialize(assign values) to the data members of the class when an object of class is created.In Python the __init__() method is called the constructor and is always called when an object is created.

Partitioning programs and problems into smaller pieces is known as... divide & conquer

Divide & Conquer

Hides details of the implementation so that the program is easier to read and write... encapsulation

Encapsulation

An algorithm should be written for the programming language it will be implemented in. TRUE or FALSE?

FALSE

Functions cannot have more than one return statement. TRUE or FALSE?

FALSE

Indexing a string always starts at 1. TRUE or FALSE?

FALSE

Lambda contains return statements. TRUE or FALSE?

FALSE

The input() function returns an int. TRUE or FALSE?

FALSE

A dictionary key value pair can be called by its index. True or False?

False

A dictionary key-value pair is called by its index. True or False?

False

A function without a return statement automatically returns false. True or False?

False

A set contains an unordered collection of unique and immutable objects. True or False?

False

All loops require break statements to end the loop. True or False?

False

Comprehensions can be use to make lists, dictionaries, and sets. True or False?

False

Dictionaries can have duplicate keys. True or False?

False

Indexing of strings tuples, and sets all start at 0. True or False?

False

Lists allow assignments, such as my_list[5] = 25 True or False?

False

Slicing a string isn't the same as slicing a list or tuple. True or False?

False

The chr() function converts a character into a number (ASCII value). True or False?

False

A class will commonly share attributes with another class, but with some additions or variations is known as... inheritance

Inheritance

Calling a function. We are going to __________ the function. invoke

Invoke

Names of different operator overloading functions consist of... p1 < p2 p1 <= p2 p1 == p2 p1 != p2 p1 > p2 p1 >= p2

Less than Less than or equal to Equal Not equal to Greater than Greater than or equal to

class Item: def __init__(self, name='', desc='', price=0, quantity=0) self.name = name self.description = desc self.price = price self.quantity = quantity def __str__(self): total-price = self.price*self.quantity return "{}: ${} x {} - ${}\n{}".format(self.name, self.price, self.quantity, total_price, self.description) def __add__(self, other): new_price = (self.price*self.quantity) + (other.price*other.quantity) return new_price ps5 = Item("PS5", "New Playstation Console", 400, 3) xbox = Item("Xbox", "new xbox", 500, 1) print(ps5) print() print(ps5+xbox) What is the output?

Output = PS5 $400 x 3 - $1200 New Playstation Console

x = 789 for i in x: print(i) What is the output?

Output = This will give an error because x is not iterable. "for i in x" is used to iterate the object x if it is iterable, but since x is of an int type and int isn't considered iterable.

"hello world 2021"[3:7] What is the ouput?

Output = lo w

"hello world 2021"[3::3] What is the output?

Output = lwl21

def fcn(word): if len(word) == 1: return word return word[-1] + fcn(word[:-1]) print(fcn("This is recursion")) What is the output?

Output = noisrucer si sihT

What is the output: x = 15 def func(x): print('x is', x) x = 5 print('x =', x) #return x func(x) print('x is now', x)

Output: x is 15 x = 5 x is now 15

What is the output of the following: class A: def __init__(self): self.multiply(15) print(self.i) def multiply(self, i): self.i = 4 * i; class B(A): def_init__(self): super().__init__() def multiply(self, i): self.i = 2 * i; obj = B() Obj2 = A()

Output: 30 60

What is the output of the following: class Demo: def check(self): return " Demo's check " def display(self): print(self.check()) class Demo_Derived(Demo): def check(self): return " Derived's check " Demo().display() Demo_Derived().display()

Output: Demo's check Derived's check

What is the difference between overloading and overriding?

Overloading is a method in which the same class shares the same method name of having different signatures. Is used to add more to the behavior of methods and there is no need of more than one class for method overloading. Overriding is simply by defining in the child class a method with the same name of a method in the parent class.

How do you tell a class to inherit from another class?

Parent class is the class being inherited from, also called base class. The child class is the class that inherits from another class, also called the derived class. Any class can be a parent class, so the syntax is the same as creating any other class.

copy()

Returns a copy of the set.

clear()

Removes all elements from the set.

difference_update()

Removes all elements of another set from this set.

discard()

Removes an element from the set if it is a member (does nothing if the element is not in set).

remove()

Removes an element from the set. If the element is not a member, raises a KeyError.

pop()

Removes and returns an arbitrary set element. Raises KeyError if the set is empty.

An error that occurs before the execution of a program. When code is not formatted correctly is called... syntax error

Syntax Error

A set contains an unordered collection of unique and immutable objects. TRUE or FALSE?

TRUE

Open()

The key function for working with files in Python.

What are the two most important parts of a recursive function?

The two most important parts of a recrusvie function are the base case and recursive case. The base case is a way to return without making a recursive.

Inheritance

When a class shares attributes with another class, but has some additions or changes.

Which of the following are required for a function to be considered recursive? [Select all that apply] a. A base case b. An iterative case c. A recursive case d. Default parameters

a. A base case c. A recursive case

What does the .clear() function do when called upon a dictionary? a. All items in the dictionary are removed b. Only the item passed to the function will be removed. c. Removes all items in the dictionary, then returns the entire dictionary. d. None of the above

a. All items in the dictionary are removed

If a mutable object such as a list is passed to a function, and that function modifies the object in place (for example, by appending to the list): a. Any changes to the object are reflected in the main program, since it was modified in place. b. Any changes to the object are not reflected in the main program, since changing the object creates a new one. c. The program will crash, since by definition mutable objects cannot be changed. d. An exception will be raised, because mutable objects cannot be passed to functions. e. None of the above.

a. Any changes to the object are reflected in the main program, since it was modified in place.

What is a class attribute? a. It is a variable that is shared among all of the instances of that class. They are defined within the scope of the class. b. It is a variable that is unique to each instance of the class. They are defined within the constructor of the class. c. It is a function within the class. You use dot notation for the function call (ex: class_instance.your_function() ) d. It is simply just an instance of the class.

a. It is a variable that is shared among all of the instances of that class. They are defined within the scope of the class.

What happens after the program goes outside of a with block (assuming the with block was used to open a file)? a. The file is closed. b. The file remains open for later use. c. The contents of the file are deleted. d. The file's mode switches to the next mode in the queue.

a. The file is closed.

What will be the output? d = {"john":40, "peter":45} print("john" in d) a. True b. False c. Error d. None

a. True

Which function overloads the + operator? a. __add__() b. __plus__() c. __sum__() d. None of the above

a. __add__()

Which function requires functools to be imported before you can use it? a. reduce() b. filter() c. sorted() d. map()

a. reduce()

What keyword are you supposed to put in front of every variable when dealing with them inside of a class? (the .variable_name is supposed to represent the variable after the keyword) a. this.variable_name b. this_instance.variable_name c. instance.variable_name d. self.variable_name

a. this.variable_name

Given the file car_models.txt, which of the following is the correct way to open the file for reading? Select all that apply. a. open(car_models.txt, r) b. open('car_models.txt') c. open('car_models.txt', 'r') d. open('car_models.txt', flag=READ)

b. open('car_models.txt') c. open('car_models.txt', 'r')

Which function below defines a class constructor? a. __construct__(self) b. __initial__(self) c. __init__(self) d. __cnstrctr__(self)

c. __init__(self)

Which of the following is the correct syntax for a lambda function? a. lambda expression: arguments b. def lambda expression c. lambda arguments: expression d. lambda arguments: expression 1: expression 2

c. lambda arguments: expression

Which of the following results in a syntax error? a. print(' "Once upon a time..." ') b. print("She shouted, 'Yes!' ") c. print('3\') d. print(" 'It is... acceptable.' ")

c. print('3\')

Define class Payment that stores the amount of the payment and appropriate constructor, setter, and getter. It will also include output() method that will display the amount of payment to screen. - Now payment can be done with credit card: - You will need to define Person class, that will include first and last name of person with setter methods as well. - Define class Credit that will inherit from Payment and Person and will add another instance attribute "card number" - Override output() method to display all details of the credit card transaction (amount,name)

class Payment(): def __init__(self,amount = 0): def seta(self,a): self.amount = a def geta(self): return self.amount def output(self): print(self.amount)

What is the value of the following expressions, given the following: clas_str = "CS101" description_str = "Problem Solving and Programming 1" class_str + "-" + desc_str

class_str + "-" + desc_str = CS101-Problem Solving and Programming

What is the value of the following expressions, given the following: clas_str = "CS101" description_str = "Problem Solving and Programming 1" class_str.lower()

class_str.lower() = cs101

What is the value of the following expressions, given the following: clas_str = "CS101" description_str = "Problem Solving and Programming 1" class_str[2:].isdigit()

class_str[2:].isdigit() = true

What is the value of the following expressions, given the following: clas_str = "CS101" description_str = "Problem Solving and Programming 1" class_str[::-1]

class_str[::-1] = 101SC

Write a recursive function to return multiples of 3 f(n) = 3*n #print(mult(2))#6 = 2*3 = 2+2+2 #print(mult(5))#15 = 5*3 = 5+5+5

def mult(n, counter = 1): #counter = 3 if counter == 3: #basecase #counter == 0: return 0 return n else: return n+ mult(n, counter+1) #2+4, 2+2, #n+mult(n, counter-1)

What is the value of the following expressions, given the following: clas_str = "CS101" description_str = "Problem Solving and Programming 1" desc_str[-13:-2]

desc_str[-13:-2] = Programming


Ensembles d'études connexes

Health Assessment Ch 2 Interviewing Patients to Obtain a Health Assessment

View Set

Introduction to Science and the Scientific Method

View Set

The Scarlet Letter study guide questions - McHale

View Set

3 - Cell Biology (ER, Golgi, and Vesicles)

View Set

Infection Control Chapter 28 Questions

View Set

Chapter 9 Reading Quiz FINAL (WIP)

View Set

chapter 62 management of patients with cerebrovascular disorders

View Set