COMP SCI MIDTERM 3

0.0(0)
studied byStudied by 0 people
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
Card Sorting

1/80

encourage image

There's no tags or description

Looks like no tags are added yet.

Study Analytics
Name
Mastery
Learn
Test
Matching
Spaced

No study sessions yet.

81 Terms

1
New cards

T/F: Functions with return statements, built in functions (len, max), expressions return a VALUE

True

2
New cards

T/F: Functions without a return statement, statements (assignment and conditionals), print() returns a value

False

3
New cards

What is immutable?

Strings

4
New cards

What data types can list elements store?

Any data type

5
New cards

T/F: Python allows multiple return statements in a function

True

6
New cards

What can the len() function be used on?

strings, lists, tuples, dictionaries, ranges (NOT INTEGERS)

7
New cards

T/F: The in operator checks whether a value exists in a sequence like a list or a string

True

8
New cards

Data type: [ ]

list

9
New cards

Data type: { }

Dictionary

10
New cards

Data type: ( )

Tuple

11
New cards

Index of the last element in a list of size n

n-1

12
New cards

What does range(5) print?

0,1,2,3,4

13
New cards

If the else statement is outside of a for loop, will it execute with a break statement?

The else statement only executes if the loop wasnt exited via break

14
New cards

For loops

prints each iterable in the set until going through all, or meets an if/ else condition stating to break

15
New cards

What is the difference between = and ==?

= is an assignment operator

== is for mathematic expressions or used as a comparison operator for boolean expressions

16
New cards

What is the purpose of the pass statement?

Acts as a placeholder, essentially does nothing but allows code to run without errors. Can be used if you want to add something to a function later.

17
New cards

How can you generate a list of numbers from 1-10?

x=list(range(1,11))

print(x)

#the range function makes a set of numbers but doesnt include the last number

18
New cards

What is the difference between a function argument and a function parameter?

Parameter is the placeholder name in the definition

Argument is the actual value you pass to the function when CALLING it

19
New cards

What is the output of the following code?

a = [1,2,3]

b=a

b.append(4)

print(a)

[1,2,3,4]

#B is not a duplicate of a, instead it is just being called by a different name (think of it as a nickname), but the object is still adding 4

#Think of it as Meg (or) Meghan changing her hair color, it’ll different regardless of her name

20
New cards

Using user input in a function

define a variable OUTSIDE OF the function that takes user input then set that variable equal to the argument when calling the function

21
New cards

How to make input a different data type (other than a string)?

before using keyword input, write data type (int, list, tuple, etc.)

22
New cards

Write a function count_vowels(s) that takes a string s as input and returns the number of values (a,e,i,o,u) in the string.

s= input("Provide a string: ") #define outside func

def count_vowels(s):

vowels = ["a","e","i","o","u"] #make sure vowels are in quotes

a= [ ]

for i in s.lower(): #lower will count upper case too

if i in vowels: #in will search for element in vowles

a.append(i) #adds vowel to new list

return len(a) #counts list of vowels

print(count_vowels(s))

23
New cards

Write a function named sum_of_squares that takes an integer n as input and returns the sum of squares of all integers from 1 to n.

n = int(input("Enter a number: "))

def sum_of_squares(n):

x = 0 #initializing value

for i in range(n + 1): #because range function doesnt include last value, we have to add 1

x += i**2 # using (+=) adds the value to the initial value

return x

print(sum_of_squares(n))

24
New cards

T/F: Dictionaries allow duplicate keys

False

25
New cards

T/F: The self-keyword in Python is mandatory for instance methods in a class

True

26
New cards

T/F: Encapsulation refers to restricting access to certain details of an object

True

27
New cards

T/F: The get() method in dictionaries returns None if the key is not found

True (unless you specify in the second index)

28
New cards

T/F: super() is used to call a method from the parent class

True

29
New cards

T/F: Abstract classes can create an object from a class directly

False

30
New cards

T/F: Object in Python are instances of a class

True

31
New cards

T/F: The init method must return a value

False

32
New cards

T/F: You can edit a list inside of a tuple

True

33
New cards

What method is automatically called when an object is created?

init()

34
New cards

Define Abstraction:

Hiding the implementation details while exposing the functionality

35
New cards

Describe Polymorphism:

One function or method having multiple behaviors

Allows different classes to be treated as if they are the same type, but they behave differently when you call their methods.

class Dog:

def speak(self):

print("Bark")

class Cat:

def speak(self):

print("Meow")

d= Dog()

c= Cat()

d.speak

c.speak

36
New cards

What is a class called that contain 1+ abstract methods, and is a subclass of class ABC?

An abstract class

Opposite would be a concrete class

37
New cards

Access modifiers

Public has no underscore

_ Protected

_ _ Private

38
New cards

How do you add a key-value pair to an existing dictionary?

dictionary_name[“key”]=”value”

print(dictionary_name)

#{”key”: “value”} will be added to dictionary

39
New cards

Why do we use inheritance in object-oriented programming?

A child class (also called a subclass) inherits attributes and methods from a parent class.

It creates simplicity in the code.

  • Reuse code efficiently

  • Avoid repetition

  • Build maintainable systems

  • Support polymorphism for flexibility

40
New cards

What is multiple inheritance? Give an example.

When a class inherits from more than one parent class. This allows the child class to access the attributes and methods of all parent classes.

class Flyable:

def fly(self): #method

print("I can fly!")

class Swimmable:

def swim(self): #method

print("I can swim!")

class Duck(Flyable, Swimmable): #calling both classes

def quack(self): #method

print("Quack!")

d = Duck() #instance/object

d.fly() #”I can fly"!”

d.swim()

d.quack()

41
New cards

Multi-level inheritance

When a class inherits from a class that already inherited from another class.

class Animal:

def breathe(self):

print("Breathing...")

class Mammal(Animal):

def walk(self):

print("Walking...")

class Dog(Mammal):

def bark(self):

print("Barking!")

42
New cards

T/F: classes need attributes

False

43
New cards

Method Overriding

When a child class defines a method that already exists in its parent class, but gives it a new version - will print the new child version.

44
New cards

Difference between encapsulation and abstraction.

Encapsulation is about protecting and bundling data (attributes) and methods that work on the data within a class. It hides the internal state of an object from the outside world.

Abstraction is about hiding the details and showing only the essential features of something. It helps you focus on what something does, not how it does it.

45
New cards

Abstraction in depth…

Acts as a blueprint or skeleton for child classes.

It doesn’t do anything — it just says “Hey, every class that inherits from me must define this behavior, but I won’t tell you how”

from abc import ABC, abstractmethod

class Animal(ABC): # Abstract base class

@abstractmethod

def make_sound(self):

pass

#This says: "All Animals must make a sound, but I won’t define what that sound is here."

46
New cards

How do you iterate through dictionary keys and values?

keys are returned by default using a for loop

for item in dictionary_name:

return item #returns key

to return values, use the .values() method

for item in dictionary_name.values():

return item

47
New cards

What does the .get() method do in dictionaries?

retrieves values associated with specified key, otherwise returns None unless specific in second indices

dictionary= {"apple": 1, "banana":2}

dictionary.get("apple")

#returns 1

48
New cards

Defining and using classes in Python.

class Animal:

def init(self,animal,color):

self.animal=animal

self.color=color

def appearance(self): #only need to pass on self and new attributes

return(f"This is a {self.animal} and it is {self.color}.")

monkey = Animal("monkey", "brown") #making an instance

print(monkey.appearance()) #to call you must put () after method

print(monkey.color)

49
New cards

Linear vs Binary search

Linear search is an example of the Brute Force Algorithm, going one by one until finding search item

Binary search, the list must be SORTED, and the code will start in the middle and search left if value is smaller than middle, or search right if value is larger

50
New cards

What happens if a recursive function doesnt have a base case?

It is the condition under which the function stops calling itself and begins to return a result. Without it, the recursive function will not know when to stop because there is no simplest form.

51
New cards

Write a function that merges two dictionaries

fruits= {"apple": 1, "banana": 2}

vegetable = {"carrot": 3, "celery": 4}

def merge(dict1, dict2):

merged = {} #create an empty dictionary

for key in dict1:

merged[key] = dict1[key] #adds key from dict 1 to merged dictionary

for key in dict2:

merged[key] = dict2[key]

return merged

print(merge(fruits, vegetable))

52
New cards

Write a program to count occurrences of each element in a tuple.

tup = (1,2,2,3,4,1)

d={}

for item in tup:

d[item] = d.get(item,0)+1

print(d)

53
New cards

break and continue statement

The break statement is used to exit the loop entirely, even if the loop’s condition is still True. When break is encountered, the loop terminates, and the program continues with the next statement after the loop.

The continue statement is used to skip the current iteration of the loop and move to the next iteration. When continue is encountered, the rest of the code inside the loop for that iteration is skipped, and the loop moves to the next cycle.

54
New cards

splitting

The split() method is used to break a string into a list of substrings, based on a specified delimiter. It’s commonly used to divide a sentence into words, or split data separated by commas.

sentence = "Python is awesome"

print(sentence.split())

or you can use list method to directly make split into letter

55
New cards

Returning a dictionary pair

for x, y in dictionary.items():

print(x,y)

the .items() method returns pairs

56
New cards

Write a function to count the first letter of keys in a dictionary

dictionary = {"Apple": 1, "Banana": 1, "Celery": 2}

d = {}

for key in dictionary:

first_letter = key[0]

d[first_letter] = d.get(first_letter, 0) + 1

print(d)

57
New cards

Dictionaries as counters

word = {“apple”: 1, “banana”: 2}

d = {}

for item in word:

d[item]=d.get(item,0) + 1

print(d)

58
New cards

slicing

sentence = "Python is awesome"

print(sentence [7:9]) #Extracts characters from index 7 to 8 (excluding 9)

#output “is”

59
New cards

Linear Search

def name(alist, a):

for item in alist: #in will search

if item == a:

return True

return False

60
New cards

Divide and Conquer

breaking down into smaller problems to solve individually and combing solutions to solve main problem (binary and recursive)

61
New cards

write a recursive function that recursively returns fibonacci sequence

def fibonacci(n)

if n in [1,2]:

return 1

else:

return fib(n-1) + (n-2)

62
New cards

write a factorial function that multiples itself by n-1

def factorial(n):

if n==1:

return 1

else:

return n*factorial(n-1)

63
New cards

Set

Data Structure used to store and collect unique elements

  • no defined order

  • can create through set() or {}

64
New cards

NumPy

Numerical Python, multi-dimensional container for homogeneous data

  • enable us to perform math operations on WHOLE block of data

  • can have nested sequences

  • shape: tuple indicating length

65
New cards

np.random

Submodule for generating random numbers

66
New cards

np.random.randint

used to generate random integers between an interval (low, inclusive, to high, exclusive)

  • can specify size=(row, height

67
New cards

Pandas

Made to mainly work with labeled data, like spreadsheets

68
New cards

Pandas Series

A one-dimensional array-like object containing a sequence of homogeneous values and an array of data labels (index)

  • series = pd.Series([ ])

  • works the same as a dictionary, use labels in the index to select single values (can also make dictionary a series)

  • math operators work the same as they do on arrays (can operate a whole set)

69
New cards

Boolean Indexing

to print T/F, assign variable a condition

to print only elements that meet said condition, apply new variable to old array/series

my_arr = np.array([1,-1, 2,-3, 4, 5])

positions = my_arr > 0

my_arr[positions]

70
New cards

Using comparison operators for indexing

my_arr = np.array([1, 2,-3, 4, 6,-4, 8])

positive_even_element = my_arr[(my_arr>0) & (my_arr %2 == 0)]

print(positive_even_element)

  • inside square brackets put two conditions in parenthesis

71
New cards

DataFrame

represents a rectangular table of data and contains an ordered, named collection of columns

  • can create from a dictionary using pd.DataFrame()

72
New cards

How to access column and row indexes in a Data Frame?

df.columns

df.index

73
New cards

How to access first few rows in a DataFrame?

df.head(n= )

  • default is 5

74
New cards

how to access last few rows?

df.tail(n= )

75
New cards

how to collect a random collection of data?

df.sample(n= )

76
New cards

how to access a column in a pandas DataFrame?

df[“column name”]

  • same way we get value in a dictionary

77
New cards

how to access a whole row

row = df.loc[0]

  • whatever index number

78
New cards

how to access multiple columns in a data frame?

two brackets [[ ]]

79
New cards

data filtering

df[df[“column”] > condition ]

80
New cards

inserting a column in df

df[“column name”] = np.array([ ])

  • similar to adding a new key-value pair to a dictionary

81
New cards

What’s mutable?

series, dataframes, sets, arrays