Write a class Rectangle representing a rectangle in 2 dimensions. The class should support these operations:
Rectangle(p, q) – make a rectangle with corners at Points p and q
r.area() - return the area of a rectangle
r.perimeter() - return the perimeter of a rectangle
r.contains(p) – return true if point p is inside the rectangle r
r.intersects(s) – return true if rectangle r intersects rectangle s. (Be warned: this is a bit tricky. As a hint, you might first write a helper function that determines whether two line segments intersect.)
Write a class Circle representing a circle in 2 dimensions. The class should support these operations:
Circle(p, r) – make a circle whose center is at p, with radius r
c.area() - return the area of a circle
c.circumference() – return the circumference of a circle
c.contains(p) – return true if point p is inside the circle c
Write a
class Vector
that represents a vector in n-dimensional
space. (We partially implemented this class in the lecture.)
Provide an initializer that takes a list of numbers, yielding a vector with those components.
v.add(w) should add two vectors.
v.mul(w) should multiply a scalar times a vector, yielding a new vector.
v.dot(w) method should compute the dot product of two vectors, yielding a scalar.
v.length() should compute the length of a vector.
v.angle(w) should computes the angle between two vectors in radians.
A vector should have a string representation such as "[3.25 5.02 -6.12]", with two digits after the decimal point in each component.
Write a class Date representing a month and day. The class should support these operations:
Date(m, d) – make a Date representing the given month (1 ≤ m ≤ 12) and day (1 ≤ d ≤ 31)
d.next() - return the Date after d
d.prev() - return the Date before d
d.add(n) – add n days to the given Date, wrapping past Dec 31 to Jan 1 if necessary
A Date object's string representation should look like this: "May 15".
Write a function that computes the sum of two matrices A and B, represented as lists of lists. Assert that the matrices have the same dimensions.
Write a function that computes the product of two matrices A and B, represented as lists of lists. Assert that the matrices have dimensions that are compatible for multiplication.
Write a function cycle
that takes a
list of length N representing a permutation of the integers 0, …, N
– 1. The function should return True
if the permutation is a single cycle. For example:
cycle([2, 3, 1, 0]) is True
because the permutation
0
-> 2
1 -> 3
2 -> 1
3 -> 0
is a cycle (0 -> 2 -> 1 -> 3 -> 0).
cycle([2, 3, 0, 1]) is False
because the permutation
0 -> 2
1 ->
3
2 -> 0
3 -> 1
is not a cycle (0 -> 2 -> 0, 1 -> 3 -> 1).