Question: Give the code for the following functions where the class below is given: def region_contains(self, p), def region_bounding_box(self), def rectangle_random_point(self), def region_montecarlo_volume(self, n=1000), and def

Give the code for the following functions where the class below is given: def region_contains(self, p), def region_bounding_box(self), def rectangle_random_point(self), def region_montecarlo_volume(self, n=1000), and def region_montecarlo_difference(self, other, n=1000). It must follow the exact parameters and pass the tests assigned to each function below. Insert code where it says, "YOUR CODE HERE."

import string

class Rectangle(object):

def __init__(self, *intervals, name=None):

"""A rectangle is initialized with a list, whose elements are

either Interval, or a pair of numbers.

It would be perhaps cleaner to accept only list of intervals,

but specifying rectangles via a list of pairs, with each pair

defining an interval, makes for a concise shorthand that will be

useful in tests.

Every rectangle has a name, used to depict it.

If no name is provided, we invent a random one."""

self.intervals = []

for i in intervals:

self.intervals.append(i if type(i) == Interval else Interval(*i))

# I want each rectangle to have a name.

if name is None:

self.name = ''.join(

random.choices(string.ascii_letters + string.digits, k=8))

else:

self.name = name

def __repr__(self):

"""Function used to print a rectangle."""

s = "Rectangle " + self.name + ": "

s += repr([(i.x0, i.x1) for i in self.intervals])

return s

def clone(self, name=None):

"""Returns a clone of itself, with a given name."""

name = name or self.name + "'"

return Rectangle(*self.intervals, name=name)

def __len__(self):

"""Returns the number of dimensions of the rectangle

(not the length of the edges). This is used with

__getitem__ below, to get the interval along a dimension."""

return len(self.intervals)

def __getitem__(self, n):

"""Returns the interval along the n-th dimension"""

return self.intervals[n]

def __setitem__(self, n, i):

"""Sets the interval along the n-th dimension to be i"""

self.intervals[n] = i

@property

def ndims(self):

"""Returns the number of dimensions of the interval."""

return len(self.intervals)

@property

def volume(self):

return np.prod([i.length for i in self.intervals])

class Region(object):

def __init__(self, *rectangles, name=None):

"""A region is initialized via a set of rectangles."""

self.rectangles = list(rectangles)

if name is None:

self.name = ''.join(

random.choices(string.ascii_letters + string.digits, k=8))

else:

self.name = name

def draw(self):

draw_rectangles(*self.rectangles, prefix=self.name + ":")

def __or__(self, other):

"""Union of regions."""

return Region(*(self.rectangles + other.rectangles), name=self.name + "_union_" + other.name)

def region_contains(self, p):

### YOUR CODE HERE

Region.__contains__ = region_contains

Test

assert (2, 1) in Region(Rectangle((0, 2), (0, 3)),

Rectangle((4, 6), (5, 8)))

assert (2, 1) not in Region(Rectangle((0, 1), (0, 3)),

Rectangle((4, 6), (5, 8)))

def region_bounding_box(self):

"""Returns the bounding box of the region, as a rectangle.

This returns None if the region does not contain any rectangle."""

if len(self.rectangles) == 0:

return None

### YOUR CODE HERE

Region.bounding_box = property(region_bounding_box)

Test

reg = Region(Rectangle((0, 2), (1, 3)), Rectangle((4, 6), (5, 8)))

assert reg.bounding_box == Rectangle((0, 6), (1, 8))

reg = Region(

Rectangle((0, 5), (4, 5), (1, 9)),

Rectangle((4, 20), (-2, 3), (4, 21)),

Rectangle((7, 99), (3, 7), (2, 3))

)

assert reg.bounding_box == Rectangle((0, 99), (-2, 7), (1, 21))

import random

def interval_random_point(self):

return random.uniform(self.x0, self.x1)

Interval.random_point = interval_random_point

# Or if we wanted to be concise, we could just have written:

Interval.random_point = lambda self : random.uniform(self.x0, self.x1)

def rectangle_random_point(self):

### YOUR CODE HERE

Rectangle.random_point = rectangle_random_point

Tests

r = Rectangle((0, 2), (1, 3))

for i in range(5):

p = r.random_point()

assert isinstance(p, tuple)

assert len(p) == 2

assert p in r

print(p)

import numpy as np

r = Rectangle((1, 2), (1, 6))

xs, ys = [], []

for _ in range(10000):

p = r.random_point()

assert p in r

xs.append(p[0])

ys.append(p[1])

assert np.std(xs) * 4.9 < np.std(ys) < np.std(xs) * 5.1

def region_montecarlo_volume(self, n=1000):

"""Computes the volume of a region, using Monte Carlo approximation

with n samples."""

# The solution, written without any particular trick, takes 7 lines.

# If you write a much longer solution, you are on the wrong track.

### YOUR CODE HERE

Region.montecarlo_volume = region_montecarlo_volume

Test

reg = Region(Rectangle((0, 1), (0, 4)), Rectangle((0, 4), (0, 1)))

reg.draw()

print(" 10 samples:", reg.montecarlo_volume(n=10))

print(" 100 samples:", reg.montecarlo_volume(n=100))

print(" 1000 samples:", reg.montecarlo_volume(n=1000))

print("10000 samples:", reg.montecarlo_volume(n=10000))

v = reg.montecarlo_volume(n=10000)

assert 6.2 < v < 7.8

def region_montecarlo_difference(self, other, n=1000):

"""Checks whether a region self is different from a region other, using

a Monte Carlo method with n samples. It returns either a point p that

witnesses the difference of the regions, or None, if no such point is found."""

# This can be done without hurry in 6 lines of code.

### YOUR CODE HERE

Region.montecarlo_difference = region_montecarlo_difference

def region_montecarlo_equality(self, other, n=1000):

return self.montecarlo_difference(other, n=n) is None

Region.montecarlo_equality = region_montecarlo_equality

Test

reg1 = Region(Rectangle((0, 4), (0, 2)), Rectangle((1, 2), (0, 4)), name="reg1")

reg2 = Region(Rectangle((0, 4), (0, 2)), Rectangle((1, 2), (1, 4)), name="reg2")

reg3 = Region(Rectangle((0, 4), (0, 2)), Rectangle((1, 2), (0, 3)), name="reg3")

assert reg1.montecarlo_equality(reg2)

assert not reg1.montecarlo_equality(reg3)

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!