PIC 16A Midterm

0.0(0)
Studied by 0 people
call kaiCall Kai
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
GameKnowt Play
Card Sorting

1/95

encourage image

There's no tags or description

Looks like no tags are added yet.

96 Terms

1
New cards

"What does // do in Python?"

"Floor division: divides, then rounds DOWN toward negative infinity. 987 // 100 is 9"

2
New cards

"What is -123 // 10, and why?"

"-13. Floor division rounds toward negative infinity (C++ truncates toward zero and would give -12)"

3
New cards

"What does the % operator do?"

"Remainder (modulo). 17 % 5 is 2. n % d == 0 means d divides n evenly"

4
New cards

"What does 5 <= 6 < 7 mean?"

"A chained comparison, same as 5 <= 6 and 6 < 7. Allowed in Python, not in C++"

5
New cards

"What does 3 * 'ab' give?"

"'ababab' (int times string repeats it)"

6
New cards

"Does Python have a character type?"

"No. A character is just a string of length 1, so type('abc'[0]) is str"

7
New cards

"What does ""dynamically typed"" mean?"

"Every value has a type, but a variable can be reassigned to a value of a different type"

8
New cards

"What do str(123) and int('123') give?"

"'123' (a string) and 123 (an int)"

9
New cards

"What is the role of indentation in Python?"

"It defines blocks of code (there are no braces). Missing indentation causes an IndentationError"

10
New cards

"What does range(2, 8) produce?"

"2, 3, 4, 5, 6, 7 (start included, stop excluded)"

11
New cards

"What does range(5, 0, -1) produce?"

"5, 4, 3, 2, 1 (a negative step counts down)"

12
New cards

"Why do loops use range(len(L))?"

"It produces exactly the valid indices 0 to len(L) - 1"

13
New cards

"When should you loop over indices instead of elements?"

"When you need positions, want to change the list in place (L[i] *= 2), or compare neighbors (L[i] and L[i + 1])"

14
New cards

"Does for el in L: el *= 10 change the list?"

"No. It only rebinds el. Use for i in range(len(L)): L[i] *= 10 to change the list"

15
New cards

"What does L.append(x) do?"

"Adds x to the end of L. It mutates L and returns None"

16
New cards

"What does L.pop() do?"

"Removes the last element of L and returns it"

17
New cards

"What goes wrong with grid = 2 * [[0]]?"

"Both rows are the SAME inner list object, so grid[0].append(1) changes both rows"

18
New cards

"How do you swap two list elements?"

"L[j], L[k] = L[k], L[j]"

19
New cards

"What is the difference between print and return?"

"print shows text on the screen. return gives a value back so other code can use it"

20
New cards

"What does a function return if it never reaches a return statement?"

"None"

21
New cards

"What is the early return pattern?"

"Check conditions in order and return as soon as the answer is known, so no else or flag variables are needed"

22
New cards

"What are the four steps of the accumulator pattern?"

"1) start with a neutral value 2) loop over the data 3) update the value 4) return it AFTER the loop"

23
New cards

"What is a common mistake with return in an accumulator?"

"Putting return inside the loop, which quits after the first pass"

24
New cards

"What is the search loop pattern?"

"Try candidates in order, return the first one that works, and return a default after the loop if none did"

25
New cards

"Why does lowest_divisor only check up to sqrt(n)?"

"If n has a divisor greater than 1, it has one that is at most sqrt(n)"

26
New cards

"How does prime_factorization work?"

"Repeatedly find the lowest divisor, record it, divide n by it, and stop when n reaches 1"

27
New cards

"What are the two parts of a recursive function?"

"A base case that answers directly, and a recursive case that calls the function on a smaller problem"

28
New cards

"Why write helper functions and reuse them?"

"It avoids repeating code. For example Q1b calls the Q1a function and Q2b calls the Q2a function"

29
New cards

"Does n *= -1 inside a function change the caller's variable?"

"No. ints are immutable, so it rebinds the local n only"

30
New cards

"What does a Python variable store?"

"A type and a reference (arrow) to an object"

31
New cards

"What does L2 = L1 do for lists?"

"Copies the type and the reference, so both names point to the SAME list object"

32
New cards

"What is mutation?"

"Changing the object itself (for example append). Every name pointing to that object sees the change"

33
New cards

"What is rebinding?"

"Making a name point to a different object (for example L = [1]). Other names are unaffected"

34
New cards

"Which list operations mutate?"

"append, pop, insert, L[i] = x, and sort"

35
New cards

"How are L1.append(1) and L1 = L1 + [1] different?"

"append changes the existing list. L1 + [1] builds a new list and moves L1 to it, leaving other names on the old list"

36
New cards

"Which common types are immutable?"

"int, str, bool, float, and tuple"

37
New cards

"What is L after L = [0, [1, 2]]; inner = L[1]; inner.append(3)?"

"[0, [1, 2, 3]]. inner and L[1] are the same list"

38
New cards

"What is L after L = [0, [1, 2]]; inner = L[0]; inner = 3?"

"Unchanged: [0, [1, 2]]. inner = 3 only rebinds inner"

39
New cards

"What does == check?"

"Whether two values are equal in content"

40
New cards

"What does is check?"

"Whether two names refer to the very same object"

41
New cards

"When should you use is?"

"For None checks and type checks, such as type(x) is int. Use == to compare values"

42
New cards

"What is garbage collection?"

"Python automatically deletes objects that no name or list slot refers to anymore"

43
New cards

"Are tuples mutable?"

"No. t[0] = 5 raises a TypeError"

44
New cards

"What does x, y = snake[0] do?"

"Unpacks the tuple at snake[0] into x and y"

45
New cards

"How are arguments passed to functions?"

"By object reference: the argument is assigned to the parameter (param = argument), so both names point to the same object"

46
New cards

"In def trial(L): L.append(0); L = [1], what happens to the caller's list?"

"It gets the 0 appended (mutation). L = [1] only moves the local L, so the caller never sees it"

47
New cards

"What does def f(): create?"

"A variable f whose type is function and whose reference points to a function object"

48
New cards

"What is the difference between f and f()?"

"f is the function object itself. f() calls it"

49
New cards

“How do you pass a function to another function?”

"Write its name without parentheses, like my_sort(L, leq_for_ints). Inside, call it as leq(a, b)"

50
New cards

"What are the five steps when a function is called?"

"1) scope created 2) locals created 3) arguments assigned to parameters 4) body runs 5) scope destroyed and unreferenced objects garbage collected"

51
New cards

"When is a name local inside a function?"

"When it is a parameter, or when it is assigned to anywhere in the function"

52
New cards

"What happens if a function uses a name it never assigns?"

"Python looks it up in the global scope"

53
New cards

"Why does def f(): L.append(3); L = [] give UnboundLocalError?"

"L = [] makes L local for the whole function, so L.append(3) runs before the local L has a value"

54
New cards

"Why does def f(): L.append(2) work on a global L?"

"L is never assigned inside f, so it is the global L. append mutates the global list"

55
New cards

"What is the effect of def f(): L = []; L.append(4) on a global L?"

"None. L is local, so it is a new list and the global L is untouched"

56
New cards

"Why does count += 1 on a global int inside a function fail?"

"+= counts as an assignment, so count becomes local and has no value yet (UnboundLocalError)"

57
New cards

"What is the difference between a parameter with and without a default?"

"Without a default it is required (missing it is a TypeError). With a default it is optional"

58
New cards

"Where must parameters with defaults go in a def?"

"After all parameters without defaults. def f(a = 1, b): is a SyntaxError"

59
New cards

"When is a default argument evaluated?"

"Once, when the def statement runs. The same object is reused for every call"

60
New cards

"What is the danger of def f(x, L = [])?"

"The default list is created once and shared by all calls that omit L, so changes pile up"

61
New cards

"What is the standard fix for a mutable default?"

"Use L = None, then inside write: if L is None: L = []"

62
New cards

"What is a positional argument?"

"An argument matched to a parameter by its position in the call"

63
New cards

"What is a keyword argument?"

"An argument passed by name in the call, like greeting(name='Sam')"

64
New cards

"What is the rule for mixing positional and keyword arguments?"

"Positional arguments must come first. greeting(salutation='Hi', 'Sam') is a SyntaxError"

65
New cards

"How is a keyword argument different from a default value?"

"A default is written in the def. A keyword argument is written in the call"

66
New cards

"What is the lambda syntax?"

"lambda parameters: expression. It returns the expression's value"

67
New cards

"What can a lambda contain?"

"A single expression only (no loops or multiple statements)"

68
New cards

"What is the difference between L.sort() and sorted(L)?"

"L.sort() changes L and returns None. sorted(L) returns a new list and leaves L alone"

69
New cards

"What does x = L.sort() store in x?"

"None. This is a classic bug"

70
New cards

"What does the key argument of sort and sorted do?"

"It is a function applied to each element. Elements are ordered by the values it returns"

71
New cards

"How do you sort lists by their sum?"

"LL.sort(key = lambda L: sum(L))"

72
New cards

"What does ""sort is stable"" mean?"

"Elements with equal keys keep their original relative order"

73
New cards

"Why put test cases inside if __name__ == '__main__':?"

"So they run only when you run the file directly, not when another file imports it"

74
New cards

"What are good steps for solving a coding problem?"

"1) solve a small example by hand 2) decide input and output (return vs print, mutate vs new) 3) pick a pattern 4) write comments as a skeleton 5) turn comments into code 6) test and trace"

75
New cards

"How do you debug by tracing?"

"Make a table with one row per loop pass and one column per variable. The first row that differs from what you expected shows the bug"

76
New cards

"Which pattern fits ""is every element ...?"""

"Early return: return False on the first failure, return True after the loop"

77
New cards

"Which pattern fits ""count how many"" or ""add up""?"

"The accumulator pattern"

78
New cards

"What is the difference between s.find(x) and s.index(x)?"

"Both give the position of the first match. If x is not found, find returns -1 and index raises a ValueError"

79
New cards

"What is the difference between s.split() and s.split(' ')?"

"split() splits at runs of whitespace, so extra spaces are ignored. split(' ') splits at every single space, so 'a b' gives ['a', '', 'b']"

80
New cards

"What does s.strip(chars) do, and what does it NOT do?"

"It removes any of those characters from the two ENDS of s. It does not touch characters in the middle (use replace for that)"

81
New cards

"What does sep.join(list) do?"

"Glues a list of strings into one string with sep between them. It is the opposite of split"

82
New cards

"What do the three parts of seq[start:stop:step] mean?"

"Start at start, go up to but NOT including stop, moving by step. Any part can be left out. L[::-1] is the whole sequence reversed"

83
New cards

"What is the difference between L.copy() and copy.deepcopy(L)?"

"copy makes a new outer list whose slots still point to the same inner objects (shallow). deepcopy also copies the inner objects, so a list of lists becomes fully independent"

84
New cards

"What is the difference between d[key] and d.get(key, default)?"

"d[key] raises a KeyError if the key is missing. d.get(key, default) returns the default instead"

85
New cards

"What does 'x' in d check for a dictionary d?"

"Whether 'x' is a KEY of d, not a value"

86
New cards

"How do you create an empty dictionary and an empty set?"

"{} is an empty dictionary. An empty set must be written set()"

87
New cards

"What is the difference between s.remove(x) and s.discard(x)?"

"If x is not in the set, remove raises a KeyError and discard silently does nothing"

88
New cards

"Why is x in s much faster for a set or dictionary than for a list?"

"Sets and dictionaries use a hash table (about O(1) per lookup). A list checks every element one by one (O(n))"

89
New cards

"How do you write a tuple with one element?"

"(8,) with the comma. (8) is just the int 8"

90
New cards

"Can a tuple's contents change?"

"You can't reassign its slots (t[0] = 1 is a TypeError), but if a slot refers to a mutable object like a list, that object can still be mutated"

91
New cards

"What are tuple packing and unpacking?"

"Packing builds a tuple (t = a, b, c). Unpacking assigns its elements to variables (x, y, z = t). Multiple assignment and swaps like a, b = b, a work this way"

92
New cards

"Which values can be dictionary keys or set elements?"

"Hashable ones: roughly immutable all the way down (int, str, tuples of those). Lists, dicts, and sets are not, and neither is a tuple that contains a list"

93
New cards

"What are the three comprehension forms?"

“[expr for …] makes a list, {expr for …} makes a set, and {key: value for …} makes a dictionary"

94
New cards

"How do you turn a loop that appends into a comprehension?"

"Write the loop the long way first. Then write the appended expression, followed by the for loops and if on one line without colons: [expr for … if …]"

95
New cards

"In a nested comprehension, how do you tell which loop is outer?"

"Outer is the loop written first in a flat comprehension, or the one outside the inner brackets in a nested one. [[… for j …] for i …] has i outer"

96
New cards

"Why does [lambda x: i * x for i in range(4)] go wrong, and what is the fix?"`

"The lambda looks up i when it is CALLED, by which time i is the final value. Fix it with a default argument, lambda x, j = i: j * x, which captures i at definition time"