1/95
Looks like no tags are added yet.
"What does // do in Python?"
"Floor division: divides, then rounds DOWN toward negative infinity. 987 // 100 is 9"
"What is -123 // 10, and why?"
"-13. Floor division rounds toward negative infinity (C++ truncates toward zero and would give -12)"
"What does the % operator do?"
"Remainder (modulo). 17 % 5 is 2. n % d == 0 means d divides n evenly"
"What does 5 <= 6 < 7 mean?"
"A chained comparison, same as 5 <= 6 and 6 < 7. Allowed in Python, not in C++"
"What does 3 * 'ab' give?"
"'ababab' (int times string repeats it)"
"Does Python have a character type?"
"No. A character is just a string of length 1, so type('abc'[0]) is str"
"What does ""dynamically typed"" mean?"
"Every value has a type, but a variable can be reassigned to a value of a different type"
"What do str(123) and int('123') give?"
"'123' (a string) and 123 (an int)"
"What is the role of indentation in Python?"
"It defines blocks of code (there are no braces). Missing indentation causes an IndentationError"
"What does range(2, 8) produce?"
"2, 3, 4, 5, 6, 7 (start included, stop excluded)"
"What does range(5, 0, -1) produce?"
"5, 4, 3, 2, 1 (a negative step counts down)"
"Why do loops use range(len(L))?"
"It produces exactly the valid indices 0 to len(L) - 1"
"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])"
"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"
"What does L.append(x) do?"
"Adds x to the end of L. It mutates L and returns None"
"What does L.pop() do?"
"Removes the last element of L and returns it"
"What goes wrong with grid = 2 * [[0]]?"
"Both rows are the SAME inner list object, so grid[0].append(1) changes both rows"
"How do you swap two list elements?"
"L[j], L[k] = L[k], L[j]"
"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"
"What does a function return if it never reaches a return statement?"
"None"
"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"
"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"
"What is a common mistake with return in an accumulator?"
"Putting return inside the loop, which quits after the first pass"
"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"
"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)"
"How does prime_factorization work?"
"Repeatedly find the lowest divisor, record it, divide n by it, and stop when n reaches 1"
"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"
"Why write helper functions and reuse them?"
"It avoids repeating code. For example Q1b calls the Q1a function and Q2b calls the Q2a function"
"Does n *= -1 inside a function change the caller's variable?"
"No. ints are immutable, so it rebinds the local n only"
"What does a Python variable store?"
"A type and a reference (arrow) to an object"
"What does L2 = L1 do for lists?"
"Copies the type and the reference, so both names point to the SAME list object"
"What is mutation?"
"Changing the object itself (for example append). Every name pointing to that object sees the change"
"What is rebinding?"
"Making a name point to a different object (for example L = [1]). Other names are unaffected"
"Which list operations mutate?"
"append, pop, insert, L[i] = x, and sort"
"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"
"Which common types are immutable?"
"int, str, bool, float, and tuple"
"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"
"What is L after L = [0, [1, 2]]; inner = L[0]; inner = 3?"
"Unchanged: [0, [1, 2]]. inner = 3 only rebinds inner"
"What does == check?"
"Whether two values are equal in content"
"What does is check?"
"Whether two names refer to the very same object"
"When should you use is?"
"For None checks and type checks, such as type(x) is int. Use == to compare values"
"What is garbage collection?"
"Python automatically deletes objects that no name or list slot refers to anymore"
"Are tuples mutable?"
"No. t[0] = 5 raises a TypeError"
"What does x, y = snake[0] do?"
"Unpacks the tuple at snake[0] into x and y"
"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"
"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"
"What does def f(): create?"
"A variable f whose type is function and whose reference points to a function object"
"What is the difference between f and f()?"
"f is the function object itself. f() calls it"
“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)"
"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"
"When is a name local inside a function?"
"When it is a parameter, or when it is assigned to anywhere in the function"
"What happens if a function uses a name it never assigns?"
"Python looks it up in the global scope"
"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"
"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"
"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"
"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)"
"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"
"Where must parameters with defaults go in a def?"
"After all parameters without defaults. def f(a = 1, b): is a SyntaxError"
"When is a default argument evaluated?"
"Once, when the def statement runs. The same object is reused for every call"
"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"
"What is the standard fix for a mutable default?"
"Use L = None, then inside write: if L is None: L = []"
"What is a positional argument?"
"An argument matched to a parameter by its position in the call"
"What is a keyword argument?"
"An argument passed by name in the call, like greeting(name='Sam')"
"What is the rule for mixing positional and keyword arguments?"
"Positional arguments must come first. greeting(salutation='Hi', 'Sam') is a SyntaxError"
"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"
"What is the lambda syntax?"
"lambda parameters: expression. It returns the expression's value"
"What can a lambda contain?"
"A single expression only (no loops or multiple statements)"
"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"
"What does x = L.sort() store in x?"
"None. This is a classic bug"
"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"
"How do you sort lists by their sum?"
"LL.sort(key = lambda L: sum(L))"
"What does ""sort is stable"" mean?"
"Elements with equal keys keep their original relative order"
"Why put test cases inside if __name__ == '__main__':?"
"So they run only when you run the file directly, not when another file imports it"
"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"
"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"
"Which pattern fits ""is every element ...?"""
"Early return: return False on the first failure, return True after the loop"
"Which pattern fits ""count how many"" or ""add up""?"
"The accumulator pattern"
"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"
"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']"
"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)"
"What does sep.join(list) do?"
"Glues a list of strings into one string with sep between them. It is the opposite of split"
"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"
"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"
"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"
"What does 'x' in d check for a dictionary d?"
"Whether 'x' is a KEY of d, not a value"
"How do you create an empty dictionary and an empty set?"
"{} is an empty dictionary. An empty set must be written set()"
"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"
"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))"
"How do you write a tuple with one element?"
"(8,) with the comma. (8) is just the int 8"
"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"
"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"
"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"
"What are the three comprehension forms?"
“[expr for …] makes a list, {expr for …} makes a set, and {key: value for …} makes a dictionary"
"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 …]"
"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"
"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"