def test_vector(self): v1 = Vector(7, 4) v2 = Vector(-6, 3) self.assertEqual("%s" % v1, "Vector(7.0, 4.0)") self.assertEqual("%s" % v2, "Vector(-6.0, 3.0)") # length should be sqrt(7**2 + 4**2) = 8.062 self.assertAlmostEqual(v1.norm(), 8.062, places=3) # Create a unit vector and test its length v1u = v1.unit_vector() self.assertAlmostEqual(v1u.norm(), 1.00, places=3) v3 = v1 * 6.4 self.assertTrue(isinstance(v3, Vector)) # v3 length = 8.062(6.4) = 51.597 self.assertAlmostEqual(v3.norm(), 51.597, places=2) # v1 + v2 = (1, 7); length = 7.071 v4 = v1 + v2 self.assertAlmostEqual(v4.norm(), 7.071, places=3) # Dot product of v1, v2 = (7)(-6) + (4)(3) = -30 self.assertAlmostEqual(v1.dot(v2), -30.0, places=3) self.assertAlmostEqual(v2.dot(v1), -30.0, places=3) # Cross product of v1 x v2 = (7)(3) - (-6)(4) = 45 self.assertAlmostEqual(v1.cross(v2), 45.0, places=3) # Cross product of v2 x v1 = (-6)(4) - (7)(3) = -45 self.assertAlmostEqual(v2.cross(v1), -45.0, places=3) v5 = v1.perp() self.assertAlmostEqual(v5[0], -4.0, places=3) self.assertAlmostEqual(v5[1], 7.0, places=3)
def walk(steps): loc = Point(0, 0) direc = Vector(0, 1, 0) for turn, dist in moves(steps): if turn == 'R': direc = -Vector.k().cross(direc) else: direc = direc.cross(-Vector.k()) loc += dist * direc return loc
def walk2(steps): loc = Point(0, 0) visited = {loc} direc = Vector(0, 1, 0) for turn, dist in cycle(moves(steps)): if turn == 'R': direc = -Vector.k().cross(direc) else: direc = direc.cross(-Vector.k()) for _ in range(dist): loc += direc if loc in visited: return loc else: visited.add(loc)
def paint(codes, start=0): c = Computer(codes) loc = Point(0, 0) direc = Vector(0, 1, 0) panels = {loc: start} while c.running: c.run([panels.get(loc, 0)]) turn = c.output.pop() color = c.output.pop() panels[loc] = color if turn == 0: # Turn left direc = Vector.k().cross(direc) elif turn == 1: # Turn right direc = direc.cross(Vector.k()) loc += direc return panels