# P1. def ones(n): if n == 0: return 0 else: if n % 10 == 1: return 1 + ones(n // 10) else: return ones(n // 10) # P2. def make_reporter(value): def reporter(other_value): if other_value < value: print("smaller") elif other_value > value: print("larger") return reporter # P3. class Bus: def __init__(self,stops): self.stops = stops self.current = 0 self.passengers = 0 def pick_up(self): if self.stops[self.current] > 0: self.stops[self.current] -= 1 self.passengers += 1 def drop_off(self): if self.passengers > 0: self.passengers -= 1 self.stops[self.current] += 1 def next_stop(self): if self.current < len(self.stops) - 1: self.current += 1 else: self.stops[self.current] += self.passengers self.passengers = 0 self.current = 0 # P4. from math import sqrt class Car: def __init__(self, mpg, tank): self.x = 0.0 self.y = 0.0 self.mpg = mpg self.tank = tank self.gas = tank def driveTo(self, newX, newY): dx = self.x - newX dy = self.y - newY distance = sqrt(dx**2 + dy**2) if self.gas < distance / self.mpg: return False else: self.gas -= distance / self.mpg self.x = newX self.y = newY return True class Delivery(Car): def __init__(self): Car.__init__(self, 15, 50) def idle(self, minutes): self.gas = max(0.0, self.gas - 2.0 * minutes / 60.0) # P5. class Node: def __init__(self,value): self.value = value self.next = None class LinkedList: def __init__(self): self.first = None def append(self,value): if self.first is None: self.first = Node(value) else: current = self.first while current.next is not None: current = current.next current.next = Node(value) def apply(self, f): current = self.first while current is not None: current.value = f(current.value) current = current.next