Lite / Intelligent Robotic Systems / Term 1 worksheet
Worksheet: Intelligent Robotic Systems, term 1
Name: Date:
Week 1: One script is not a system
1. units.py defines cm_to_m. Which line lets another file call cm_to_m(250) with no prefix?
- import units
- from units import cm_to_m
- import cm_to_m from units
- include units
2. In a package with no circular imports, which module's changes need the MOST re-testing elsewhere?
- main.py, the entry point at the top
- A low-level utility that many modules import
- A test file
- It is always the same for every module
3. grid.py imports planner.py so GridMap can call bfs, and planner.py imports grid.py. What is the best fix?
- Swap the order of the import lines
- Let main.py call bfs(grid, start, goal), so grid.py no longer imports planner
- Copy bfs into grid.py as well
- Put both files' code into one big file
4. planner.py contains def _neighbours_in_bounds(...). What does the leading underscore tell other programmers?
- The function is faster
- It is an internal helper, not part of the module's interface
- Python will refuse to import it
- It is a constant
5. io_csv.py ends with print(load_map('mars.csv')) at the top level. What happens when planner tests run 'import io_csv'?
- Nothing, imports never run code
- The map is loaded and printed during the import, which may fail if mars.csv is missing
- Python asks which part to run
- Only the function definitions are copied
Week 1: Functions that keep their promises
1. Docstring: 'Returns the distance.' What is the most important thing missing for an engineer using it?
- The author's name
- The units of the inputs and of the returned distance
- How long the function took to write
- A joke
2. Using battery_runtime_h from the worked example, what does battery_runtime_h(3000, 750) return, in hours?
Answer: h
3. Which function design is best for a sensor-log tool?
- process() reads the file, filters spikes, averages and prints the answer
- load_log(path), remove_spikes(values, limit) and mean(values), each returning a value
- One function per line of code
- A global variable that every function changes
4. wheel_rpm(speed_m_s, diameter_m) is called with diameter_m = -0.1. Which response best keeps the contract?
- Use abs(diameter) silently
- raise ValueError('diameter_m must be positive, got -0.1')
- Return None
- Return 0
5. A function prints the average current instead of returning it. What can't you do?
- Read the number on screen
- Use the average in the next calculation or check it with assert
- Call the function
- Give it a docstring
Week 1: Tests that catch you before the robot does
1. Which input is the best edge case for a function that returns the last reading of a sensor log?
- A log with 50 readings
- A log with exactly one reading, and an empty log
- A log with 51 readings
- A log of very large readings
2. Which test is safest for mean([0.1, 0.2]) (true answer 0.15)?
- assert mean([0.1, 0.2]) == 0.15
- assert abs(mean([0.1, 0.2]) - 0.15) < 1e-9
- assert mean([0.1, 0.2])
- print(mean([0.1, 0.2]))
3. Why put demo code under if __name__ == "__main__":?
- It makes the code run faster
- So the demo runs when the file is executed directly but not when it is imported
- Python requires it in every file
- It hides the code from other programmers
4. assert clamp(-5, 0, 100) == 0 fails with clamp returning 100. What is the most likely bug?
- The test is wrong
- low and high are swapped somewhere inside clamp
- Python's max function is broken
- Negative numbers can't be clamped
5. Which set of tests gives the most confidence for clamp(value, low, high)?
- One test with a typical value
- Inside, below, above, exactly on each limit, and low > high raising ValueError
- Ten tests all inside the range
- No tests, because the code is short
Week 2: One blueprint, many sensors
1. Using RangeSensor from the worked example, s = RangeSensor('left', 3); s.record(40); s.record(46). What does s.mean() return?
Answer: cm
2. Inside record(self, raw_cm), what is self when you call rear.record(80)?
- The RangeSensor class
- The rear object
- The number 80
- A copy of front
3. Which class definition gives each sensor its own readings list?
- readings = [] in the class body
- self.readings = [] inside __init__
- global readings
- readings = [] inside record
4. RangeSensor.unit = "cm" is a class attribute. After front = RangeSensor('front', 2), what is front.unit?
- 'cm', found on the class
- An AttributeError, because __init__ never set it
- None
5. rear = RangeSensor('rear', -1); rear.mean() is called before any readings. With the worked example's code, what happens?
- Returns 0
- Raises ValueError('rear has no readings yet')
- Returns -1
- Raises ZeroDivisionError
Week 2: Objects that guard their own limits
1. With the worked example's Motor('arm', 2400), what does set_speed(2650) return?
Answer: rpm
2. Which is an invariant for an inventory Part object?
- quantity is always ≥ 0
- quantity changed recently
- The class has three methods
- description is printed in capitals
3. Motor defines rpm with @property and no setter. What does m.rpm = 3500 do?
- Sets the speed to 3500
- Clamps to max_rpm
- Raises AttributeError
- Silently does nothing
4. part.withdraw(5) is called when quantity is 3. What should a well-designed method do?
- Set quantity to -2
- Set quantity to 0 and say nothing
- Raise ValueError and leave quantity at 3
- Delete the part
5. Which test best checks Motor's invariant?
- assert m.set_speed(1500) == 1500 only
- Call set_speed with values below, inside, on and above the limits and assert 0 <= m.rpm <= m.max_rpm after each
- Print m.rpm and look at it
- Check that the class has a method called set_speed
Week 2: Object or function? Choosing the clearer design
1. mm_to_inches(mm) converts a length. Class or function?
- A class, so it can be extended later
- A plain function: one input, one output, no state
- A global variable
2. Using the worked example's GridMap with rows ['..#', '...', '#..'], how many neighbours does cell (2, 2) have?
Answer: cells
3. A Robot holds two Motor objects and a RangeSensor. What is this design called?
- Inheritance
- Composition (a robot has motors)
- Recursion
- A circular import
4. Which situation most strongly suggests writing a class?
- Five functions all take the same (cells, width, height) arguments and must agree on what a wall is
- A function that squares a number
- A loop that runs ten times
- A single print statement
5. Why might bfs(grid, start, goal) be a function rather than a GridMap method?
- Functions are always faster
- So the same planner works on any map object that provides neighbours(), and the map stays small
- Methods can't take parameters
- Python forbids methods that return lists
Week 3: Slice, filter, transform: lists at speed
1. A wheel encoder log is readings = [1, 53, 98, 96, 28, 61, 72, 43, 99]. What does sum(readings[3:4]) evaluate to?
Answer:
2. A log has 3,000 samples at 50 Hz. Which slice gives the last 10 seconds?
- log[-10:]
- log[-500:]
- log[2500:2999]
- log[:500]
3. Which comprehension gives the masses (kg) of parts heavier than 0.5 kg, from masses_g in grams?
- [m / 1000 for m in masses_g if m > 500]
- [m for m in masses_g if m / 1000]
- [m > 500 for m in masses_g]
- [m / 1000 if m > 500 for m in masses_g]
4. A wheel encoder log is readings = [67, 75, 95, 45, 62, 53, 2, 53]. What does len(readings[0:5:2]) evaluate to?
Answer:
5. path has 8 waypoints. Which expression raises IndexError?
- path[7]
- path[-8]
- path[8]
- path[5:20]
Week 3: From CSV file to records you can query
1. row = {'run': '4', 'current_a': '1.5'} from DictReader. What does row['run'] + 1 do?
- Returns 5
- Returns '41'
- Raises TypeError: can only concatenate str to str
- Returns 4.0
2. In the worked example, if the empty current for run 4 is fixed to 1.75, what is motor B's average current (3 decimal places)?
Answer: A
3. Some rows have current 'n/a'. Which policy is best for an engineering report?
- Treat them as 0 A
- Skip them, count them, and state the count in the report
- Delete the CSV and start again
- Replace them with the average so the chart looks complete
4. Which line adds current to a per-motor list, creating the list the first time a motor appears?
- by_motor[motor] = current
- by_motor.setdefault(motor, []).append(current)
- by_motor.append(motor, current)
- by_motor[motor].append(current)
5. A log of motor temperature (°C) reads xs = [42, 50, 49, 47, 47, 44, 43, 44, 47]. What is the mean, statistics.mean(xs)? Give 2 decimal places.
Answer:
Week 3: Module check: the stores audit
1. recorded has keys {A, B, C}; counted has keys {B, C, D}. What is recorded.keys() - counted.keys()?
- {A}
- {D}
- {A, D}
- {B, C}
2. In the worked example, how many M3 bolts are missing from the shelf compared with the record?
Answer: bolts
3. Which structure makes audit() easiest to test?
- audit() reads the files, compares and prints
- audit() takes two dicts and returns lists; loading and printing are separate functions
- audit() uses global variables set by the loader
- All code in one long script with no functions
4. A log of motor temperature (°C) reads xs = [63, 66, 59, 62, 60, 54, 60]. What is the median, statistics.median(xs)? Give 2 decimal places.
Answer:
5. A wheel encoder log is readings = [45, 5, 63, 55, 46, 46, 16, 12, 19, 44]. What does readings[2] evaluate to?
Answer:
6. Which report line is most useful to the lab manager?
- 'Some parts are wrong.'
- 'M3-BOLT: recorded 120, counted 96 (24 short)' listed first because it is the largest shortfall
- A printout of both dicts
- 'Audit complete.'
Week 4: List, tuple, set or dict? Pick the right container
1. You need the stock quantity for any part number, looked up thousands of times. Which container?
- A list of quantities
- A dict {part_no: qty}
- A set of part numbers
- A tuple of tuples, scanned each time
2. visited = set(); visited.add([3, 7]). What happens?
- The cell is added
- TypeError: unhashable type: 'list'
- The set becomes [3, 7]
- Two items, 3 and 7, are added
3. A list holds 50,000 part numbers in random order. Checking a part that is NOT in the list: how many comparisons does 'p in parts' make?
Answer: comparisons
4. A planned path must keep its waypoints in order and may visit the same waypoint twice. Which container?
- set
- list
- dict
- Nothing built in can do this
5. stock = {'M3-BOLT': 120}. What does stock.get('M4-BOLT', 0) return?
- KeyError
- 0
- None
- 120
Week 4: Stacks and queues: who goes next?
1. A robot cell queues jobs in arrival order: from collections import deque; q = deque(); q.append(27); q.append(49); q.popleft(); q.append(37); q.popleft(). What value does the final q.popleft() return?
Answer:
2. An editor's undo button should reverse the most recent change first. Which structure?
- A queue
- A stack
- A set
- A dict
3. Why use deque.popleft() instead of list.pop(0) for a long job queue?
- pop(0) returns the wrong item
- pop(0) shifts every remaining item, so it gets slower as the list grows; popleft() is O(1)
- deque uses less memory in all cases
- list.pop(0) doesn't exist
4. An editor keeps an undo stack of waypoint ids: s = []; s.append(38); s.append(23); s.append(27); s.pop(); s.append(33); s.pop(); s.append(3); s.pop(). What value does the final s.pop() return?
Answer:
5. What does 'while q:' do when q is an empty deque?
- Runs forever
- Skips the loop body, because an empty deque is falsy
- Raises IndexError
- Waits for an item
Week 4: Breadth-first search: a queue explores a map
1. On an open 6-row × 9-column grid, BFS plans from (0, 0) to (5, 8). How many moves are in its path?
Answer: moves
2. What would change if BFS used a stack (pop the newest cell) instead of a queue?
- Nothing
- It would become depth-first search: it still explores, but the first path found need not be the shortest
- It would find shorter paths
- It would crash
3. Why mark a cell visited when it is ADDED to the queue, rather than when it is taken out?
- It looks neater
- Otherwise the same cell can be queued many times by different neighbours, wasting time and memory
- Python requires it
- So the path is reversed
4. The goal is completely surrounded by walls. What does BFS do?
- Loops forever
- Visits every cell reachable from the start, empties the queue and reports no path
- Walks through the wall
- Returns the start cell
5. A robot cell queues jobs in arrival order: from collections import deque; q = deque(); q.append(3); q.append(28); q.append(23); q.popleft(); q.popleft(); q.popleft(); q.append(23); q.popleft(). What value does the final q.popleft() return?
Answer:
Week 5: Halve it again: binary search
1. A sorted list holds 500 part numbers. Binary search compares the target with one middle element per loop and halves the range each time. In the worst case (including a target that is not there), how many elements does it compare with the target?
Answer: comparisons
2. Binary search runs on the unsorted list [40, 10, 30, 20] looking for 40. What happens?
- It finds 40
- It reports 'not found' even though 40 is there
- It sorts the list first
- It raises an error
3. A sorted list holds 50 calibration points. Binary search compares the target with one middle element per loop and halves the range each time. In the worst case (including a target that is not there), how many elements does it compare with the target?
Answer: comparisons
4. Linear search on an unsorted list of 4,096 sensor ids, looking for one that is absent. How many comparisons?
Answer: comparisons
5. A student writes 'while lo < hi:' instead of 'while lo <= hi:'. What goes wrong?
- Nothing
- When the range shrinks to one item, the loop stops without checking it, so that item can be missed
- The loop never ends
- It searches the list twice
Week 5: Insertion sort: tidy as you go
1. Part masses (g) arrive as a = [32, 59, 17, 37, 44, 26]. They are sorted with insertion sort, where each new key moves left while j >= 0 and a[j] > key. Counting every evaluation of a[j] > key, how many comparisons are made?
Answer: comparisons
2. How many comparisons does insertion sort make on a reversed list of 10 items?
Answer: comparisons
3. Part masses (g) arrive as a = [36, 35, 27, 11, 5]. They are sorted with insertion sort, where each new key moves left while j >= 0 and a[j] > key. Counting every evaluation of a[j] > key, how many comparisons are made?
Answer: comparisons
4. A 1,000-item log is sorted except for two neighbouring entries that are swapped. Roughly how many comparisons does insertion sort make?
- About 1,000
- About 500,000
- About 10,000
- Exactly 2
5. Two runs both drew 1.5 A; run 4 is listed before run 9. After a stable sort by current, which comes first?
- Run 4
- Run 9
- It is random
Week 5: Sort once, search many: when sorting pays
1. Linear search averages n/2 comparisons. For n = 2,000 items and k = 30 lookups, about how many comparisons in total?
Answer: comparisons
2. You must repeatedly list every part number between 2000 and 2100. Which preparation is best?
- A set
- Sort once, then binary-search for 2000 and read forwards
- Linear search each time
- A dict of part numbers to quantities
3. A sorted list holds 50 calibration points. Binary search compares the target with one middle element per loop and halves the range each time. In the worst case (including a target that is not there), how many elements does it compare with the target?
Answer: comparisons
4. You need to check ONE part number in an unsorted list of 50,000, once. Best plan?
- Sort, then binary search
- Build a set first
- Linear search
- Sort twice to be safe
5. Using cost models linear = k·n/2 and sorted = n·log₂n + k·log₂n, with n = 256, what is the smallest whole number of searches k for which sorting first is cheaper?
Answer: searches
Week 6: Count the steps before you time them
1. A program is comparing every pair of waypoints. Its step count is measured with: count = sum(1 for i in range(0, 266, 10)). What value does count hold?
Answer: steps
2. A program is filling a cost table for a route planner. Its step count is measured with: count = sum(1 for i in range(10) for j in range(6)). What value does count hold?
Answer: steps
3. A program is scanning a sensor log. Its step count is measured with: count = sum(1 for i in range(36) for j in range(i)). What value does count hold?
Answer: steps
4. pair_checks(1000) is 499,500. About how big is pair_checks(2000)?
- About 1 million
- About 2 million
- About 4 million
- About 999,000
5. One loop over n readings filters spikes; a second loop over n readings averages them. How many loop passes in total?
- n
- 2n
- n²
- n(n − 1)/2
Week 6: Big-O: the shape of growth
1. An exact count is T(n) = 7n + 3n·log₂n + 12. What is its big-O?
- O(n)
- O(n log n)
- O(7n)
- O(12)
2. Timing tests show a collision checker grows like n and takes 5 ms for n = 4096. Assuming that growth holds, predict its time for n = 8192, in ms.
Answer: ms
3. Timing tests show a parts-matching script grows like n² and takes 12 ms for n = 1024. Assuming that growth holds, predict its time for n = 4096, in ms.
Answer: ms
4. Which list is in order from slowest-growing to fastest-growing?
- n, log n, n², n log n
- log n, n, n log n, n²
- n², n log n, n, log n
- 1, n², n, log n
5. Algorithm X is O(n log n) and Y is O(n²). Which statement is true?
- X is always faster than Y
- X will be faster for large enough n, but Y may be faster for small n
- They are equally fast
- Y is always faster
Week 6: Module check: measure growth, then explain it
1. Times: 30 ms at n = 5,000 and 240 ms at n = 10,000. Estimate the exponent p in T ≈ c·n^p.
Answer:
2. Which timing method is most trustworthy?
- Run once and report the time
- Run five times per size, report the best (or median), change only n
- Time each size on a different computer
- Time while also downloading a large file
3. Timing tests show a parts-matching script grows like n² and takes 12 ms for n = 1024. Assuming that growth holds, predict its time for n = 4096, in ms.
Answer: ms
4. A program is scanning a sensor log. Its step count is measured with: count = sum(1 for i in range(46) for j in range(i, 46)). What value does count hold?
Answer: steps
5. Big-O predicts O(n), but doubling n multiplies your measured time by 4. What is the best next step?
- Trust big-O and ignore the timings
- Look for a hidden inner loop, such as 'x in some_list' inside the main loop
- Buy a faster computer
- Report O(n) anyway
6. Which of these does big-O NOT tell you?
- How the cost grows as n grows
- How long the code takes in seconds on your laptop at n = 100
- Which of two algorithms wins for very large n (if their big-O differ)
- That doubling n roughly quadruples an O(n²) cost
Week 7: Bisection: trap the answer, halve the trap
1. A cable tension must satisfy f(x) = x**2 - 11 = 0. Bisection starts on [1, 4] (f(1) < 0 < f(4)), tests the midpoint each step and keeps the half where the sign changes. What midpoint is tested in step 2? Give 4 decimal places.
Answer:
2. Bisection starts from the bracket [0, 2] and stops once the bracket width is at most 0.05. What is the smallest number of steps that guarantees this?
Answer: steps
3. Bisection starts from the bracket [1, 3] and stops once the bracket width is at most 0.001. What is the smallest number of steps that guarantees this?
Answer: steps
4. A cable tension must satisfy f(x) = x**2 - 7 = 0. Bisection starts on [1, 4] (f(1) < 0 < f(4)), tests the midpoint each step and keeps the half where the sign changes. What midpoint is tested in step 4? Give 4 decimal places.
Answer:
5. f(x) = (x − 1)² on [0, 3]. Why can't bisection start?
- The root is outside the bracket
- f(0) and f(3) are both positive, so there is no sign change to trap
- Squares can't be computed numerically
- The bracket is too wide
Week 7: Newton's method: ride the tangent
1. A microcontroller finds a vector length L = √12 with Newton's method on f(x) = x**2 - 12, using x = x - (x**2 - 12) / (2*x). Starting from x0 = 1, what is x after 2 iterations? Give 4 decimal places.
Answer:
2. A microcontroller finds a vector length L = √3 with Newton's method on f(x) = x**2 - 3, using x = x - (x**2 - 3) / (2*x). Starting from x0 = 5, what is x after 1 iteration? Give 4 decimal places.
Answer:
3. Newton's method on f(x) = x² − 4 starts at x₀ = 0. What happens?
- It converges to 2
- It converges to −2
- It fails: f′(0) = 0, so the update divides by zero
- It converges slowly
4. Which statement compares bisection and Newton fairly?
- Newton is always better
- Bisection is guaranteed given a sign change but slow; Newton is much faster near a root but can fail from a poor start
- Bisection needs the derivative
- They converge at the same rate
5. Newton's method on f(x) = x³ − 2x − 5 from x₀ = 2. What is x₁ (4 decimal places)?
Answer:
Week 7: Speed from position, distance from speed: calculus on samples
1. A linear-axis encoder logs position every 0.1 s: x = [11, 20, 29, 32, 38, 45] mm. Estimate the speed at sample index 4 using a forward difference (x[i+1] - x[i]) / h, in mm/s.
Answer: mm/s
2. A rover logs wheel speed every 2 s: v = [1, 1, 5, 5.5] m/s. Using the trapezium rule, how far did it travel between the first and last sample, in metres?
Answer: m
3. A rover logs wheel speed every 1 s: v = [3.5, 3.5, 2.5, 1, 0] m/s. Using the trapezium rule, how far did it travel between the first and last sample, in metres?
Answer: m
4. A linear-axis encoder logs position every 0.5 s: x = [15, 24, 29, 35, 40, 41] mm. Estimate the speed at sample index 3 using a central difference (x[i+1] - x[i-1]) / (2*h), in mm/s.
Answer: mm/s
5. Readings have noise up to ±0.2 mm and are 0.004 s apart. What is the largest possible noise in a forward-difference speed, in mm/s?
Answer: mm/s
6. Speed from a noisy encoder is too jumpy. Which change helps most without new hardware?
- Sample faster and difference neighbouring samples
- Difference over a longer interval, or smooth positions first
- Round positions to whole millimetres
- Integrate the speed again
Week 8: Choose the plot that answers the question
1. Does a servo's current draw rise with the load on its arm? You have 40 (load, current) pairs. Which plot?
- Line plot of current in the order measured
- Scatter plot of current against load
- Pie chart of currents
- Histogram of loads
2. How noisy is a gyro at rest? You have 5,000 readings. Which plot shows the spread best?
- A histogram of the readings
- A bar chart of the mean
- A pie chart
- A single number: the maximum
3. Which y-axis label is best?
- 'Temp'
- 'Data'
- 'Motor case temperature (°C)'
- 'y'
4. A log of motor temperature (°C) reads xs = [63, 66, 59, 62, 60, 54, 60]. What is the median, statistics.median(xs)? Give 2 decimal places.
Answer:
Week 8: Charts that lie without a single false number
1. Bars show 50 and 40 on an axis starting at 30. What is the lie factor? (Data change = (50 − 40)/40; visual change = (50 − 40)/(40 − 30).)
Answer:
2. A chart of battery life shows only months 4–6 of a 12-month trial, the months with the best results. What is the problem?
- Truncated axis
- Cherry-picked range
- Missing units
- Wrong chart type
3. When is a y-axis that doesn't start at zero acceptable?
- Never
- On a line chart where small changes matter, with clearly labelled axis values
- On any bar chart
- Whenever it makes the result look better
4. Before/after means are 41.8 and 39.2 jams a day, with day-to-day spread of ±4.2. Which caption is honest?
- 'Fix eliminates jams'
- 'Jams fell about 6% after the fix, a change smaller than the day-to-day spread; more data needed'
- 'No change'
- 'Jams fell dramatically'
5. A log of motor temperature (°C) reads xs = [42, 50, 49, 47, 47, 44, 43, 44, 47]. What is the mean, statistics.mean(xs)? Give 2 decimal places.
Answer:
Week 8: Mean, median and spread: summarising a log honestly
1. A log of battery current (A) reads xs = [20, 26, 26, 17, 21, 23, 19, 26]. What is the median, statistics.median(xs)? Give 2 decimal places.
Answer:
2. A log of motor temperature (°C) reads xs = [68, 68, 76, 77, 66]. What is the sample standard deviation, statistics.stdev(xs)? Give 2 decimal places.
Answer:
3. A log of ultrasonic range (cm) reads xs = [49, 49, 47, 44, 42, 51]. What is the sample standard deviation, statistics.stdev(xs)? Give 2 decimal places.
Answer:
4. Which report line is most honest and useful?
- 'Distance: 48 cm'
- 'Distance: median 48.1 cm, sample s.d. 0.29 cm, n = 9 (1 reading outside the 2–300 cm rated range removed)'
- 'Distance: mean 83.3 cm'
- 'Distance: between 47.6 and 400 cm'
5. Why does statistics.stdev divide by n − 1?
- To make the number bigger for safety
- Because deviations are measured from the sample mean, which sits closer to the data than the true mean; n − 1 corrects that underestimate
- It's a rounding convention
- Because the first reading doesn't count
Week 9: Project: plan a path that counts the cost
1. A path enters cells with costs 1, 1, 5, 5, 1, 1 (the start cell is free). What is its total cost?
Answer:
2. pq holds (7, A), (3, B), (5, C) via heapq. What does heapq.heappop(pq) return?
- (7, A)
- (3, B)
- (5, C)
- The last item pushed
3. On a map where every free cell costs 1, how do BFS and Dijkstra compare?
- Dijkstra finds cheaper paths
- Both find paths with the same cost (fewest moves); BFS avoids the heap's log factor
- BFS finds cheaper paths
- Dijkstra fails on uniform costs
4. An editor keeps an undo stack of waypoint ids: s = []; s.append(38); s.append(23); s.append(27); s.pop(); s.append(33); s.pop(); s.append(3); s.pop(). What value does the final s.pop() return?
Answer:
5. Why must Dijkstra's step costs be non-negative?
- heapq can't store negative numbers
- A finished cell's cost is assumed final; a negative step later could make a cheaper route to it
- Negative numbers are slower
- Python forbids them in tuples
Week 9: Project: measure the cost, plot it honestly
1. BFS expands all 3,600 cells of a 60 × 60 open map. How many cells would it expand on a 120 × 120 open map, corner to corner?
Answer: cells
2. Timing tests show a collision checker grows like n and takes 5 ms for n = 4096. Assuming that growth holds, predict its time for n = 8192, in ms.
Answer: ms
3. A program is scanning a sensor log. Its step count is measured with: count = sum(1 for i in range(36) for j in range(i)). What value does count hold?
Answer: steps
4. You plot time against map side length and see a curve bending upwards for BFS. What is the clearest honest fix?
- Smooth the curve
- Plot against number of cells (or use log–log axes) so O(V) shows as a straight line
- Remove the largest map
- Start the y-axis at the smallest time
5. Which is the best 'limitations' sentence for your report?
- 'There are no limitations.'
- 'Measured on one laptop with one 20% random obstacle pattern; the robot is modelled as a point with no turning cost, so real planning times will differ.'
- 'The code might have bugs.'
- 'Big-O is just a theory.'
Week 9: Term assessment: engineering computation, end to end
1. A program is comparing every pair of waypoints. Its step count is measured with: count = sum(1 for i in range(0, 266, 10)). What value does count hold?
Answer: steps
2. A sorted list holds 8 waypoint ids. Binary search compares the target with one middle element per loop and halves the range each time. In the worst case (including a target that is not there), how many elements does it compare with the target?
Answer: comparisons
3. Bisection starts from the bracket [1, 3] and stops once the bracket width is at most 0.001. What is the smallest number of steps that guarantees this?
Answer: steps
4. Part masses (g) arrive as a = [58, 46, 38, 32, 28]. They are sorted with insertion sort, where each new key moves left while j >= 0 and a[j] > key. Counting every evaluation of a[j] > key, how many comparisons are made?
Answer: comparisons
5. A log of motor temperature (°C) reads xs = [42, 50, 49, 47, 47, 44, 43, 44, 47]. What is the mean, statistics.mean(xs)? Give 2 decimal places.
Answer:
6. Which line inside a loop over n items makes the whole loop O(n²)?
- total += x
- queue.popleft() on a deque
- if x in seen_list:
- seen_set.add(x)
7. You need a root of a smooth f on [1, 2] (with a sign change) to 10⁻¹² quickly and safely. Best approach?
- Bisection only
- Newton from an arbitrary guess
- Bisection to get close, then Newton, rejecting Newton steps that leave the bracket
- Guess and check by hand