Question

Problem 2: Lines In class we reviewed the equation of lines: (10) Ay We also discussed variable andvariable, the former bin19 20 21 def _str__(self): return self.get line() def _mul__(self,other): 23 #TODO: IMPLEMENT FUNCTION 24 25 26 x1MyLine( (0,Session Output The intersection of y 1.00x0.00 and y --0.25x 1.25 is: The intersection of y = 1.00x + 0.00 and y = -0.80x + 5

python

1

import matplotlib.pyplot as plt

2

import numpy as np

3

4

abscissa = np.arange(20)

5

plt.gca().set_prop_cycle(

color

, [

red

,

green

,

blue

,

black

])

6

7

class MyLine:

8

9

def __init__(self,

*

args,

**

options):

10

#TO DO: IMPLEMENT FUNCTION

11

pass

12

13

def draw(self):

14

plt.plot(abscissa,self.line(abscissa))

15

16

def get_line(self):

17

return "y = {0:.2f}x + {1:.2f}".format(self.slope, self.intercept)

18

19

def __str__(self):

20

return self.get_line()

21

22

def __mul__(self,other):

23

#TO DO:IMPLEMENT FUNCTION

24

pass

25

26

x1 = MyLine((0,0), (5,5),options = "2pts")

27

x1.draw()

28

x2 = MyLine((5,0),-1/4, options = "point-slope")

29

x2.draw()

30

x3 = MyLine("(-4/5)

*

x + 5", options = "lambda")

31

x3.draw()

32

x4 = MyLine("x + 2", options = "lambda")

33

x4.draw()

34

35

print("The intersection of {0} and {1} is {2}".format(x1,x2,x1

*

x2))

36

print("The intersection of {0} and {1} is {2}".format(x1,x3,x1

*

x3))

37

print("The intersection of {0} and {1} is {2}".format(x1,x4,x1

*

x4))

38

39

40

plt.legend([x1.get_line(), x2.get_line(), x3.get_line(),x4.get_line()],

loc=

upper left

)

41

plt.show()

Problem 2: Lines In class we reviewed the equation of lines: (10) Ay We also discussed "variable and"variable, the former binding to a tuple of actual parameters and the latter allowing you to set switches. In this problem, you'll complete a Line class that not only draws the lines, but allows someone to describe the line by using two points, a point and slope, or simply the formula. For the formula, we assume the variable is always in r You'll overload the operator to find the intersection of two lines and display (x.y) when they intersection and 0 when they do not. You should assume, at a minimum the class has three instance variables (but with some choices, it might have more) 1. slope 2. intercept 3. line-A x: f(x) For example, the line y 1.3z-8 would have slope of 1.3, intercept of 8 and lineAx 1.3*x-8 (12) For this problem, you only need to implement the_init and overloaded *function. lineclass 1 import matplotlib.pyplot as plt 2 import numpy as np 3 4 abscissa np.arange(20) 5 plt.gca().set_prop_cycle( color, ['red, 'green 'blue' 'black']) 7 class MyLine def-init-(self, *args , **options): 10 #TODO: IMPLEMENT FUNCTION pass 12 13 14 15 16 def draw(self): plt.plot(abscissa,self.line(abscissa)) def get_line(self): return "y 0:.2fłx 1:.2f".format(self.slope, self.intercept) 18
19 20 21 def _str__(self): return self.get line() def _mul__(self,other): 23 #TODO: IMPLEMENT FUNCTION 24 25 26 x1MyLine( (0,0), (5,5),options"2pts" 27 x1.draw() 28 x2MyLine( (5,0),-1/4, options"point-slope") 29 x2.draw) 30 x3 MyLine("(-4/5)*X+5", options"lambda" 31 x3.draw) 32 x4 - MyLine("x + 2", optionslambda") 33 x4.draw( 34 35 print("The intersection of (o and 11 is (2)".format (x1,x2,x1*x2)) 36 print("The intersection of tO and (1 is (2)". format(x1,x3,x1*x3)) 37 print("The intersection of tO and 1 is (2)". format(x1,x4,x1*x4)) 38 39 40 plt.legend([x1.get line(), x2.get line), x3.getline),x4.get_line()], - pass loc- 'upper left') 41 plt.show) 一y·1.00x +0.00 _ y#-0.25x + 1.25 y--0.80x +5.00 20 15- y-1.00x+2.00 10 -10 0.0 2.5 5.0 7.5 10.012.5 15.0 17.5 Figure 1: Plot of 4 lines.
Session Output The intersection of y 1.00x0.00 and y --0.25x 1.25 is: The intersection of y = 1.00x + 0.00 and y = -0.80x + 5.00 is: (2.778, 2.778) The intersection of y -1.00x+0.00 and y1.00x+2.00 is: C) Deliverables Programming Problem 2 Complete the two functions Put your code for this problem in a new module named lineclass.py
0 0
Add a comment Improve this question Transcribed image text
Answer #1

#SOLUTION :

#FUNCTION 1 (Constructor __init__)

def __init__(self, slope, intercept, *args, **options):

# get current axes if user has not specified them
if not 'axes' in options:
options.update({'axes':plt.gca()})
ax = options['axes']

# if unspecified, get the current line color from the axes
if not ('color' in options or 'c' in options):
options.update({'color':ax._get_lines.color_cycle.next()})

# init the line, add it to the axes
super(ABLine2D, self).__init__([], [], *args, **options)
self._slope = slope
self._intercept = intercept
ax.add_line(self)

# cache the renderer, draw the line for the first time
ax.figure.canvas.draw()
self.__mul__(None)

# connect to axis callbacks
self.axes.callbacks.connect('xlim_changed', self.__mul__)
self.axes.callbacks.connect('ylim_changed', self.__mul__)

#FUNCTION 2 (__mul__)

def __mul__(self, other):
""" called whenever axis x/y limits change """
x = np.array(self.axes.get_xbound())
y = (self._slope * x) + self._intercept
self.set_data(x, y)
self.axes.draw_artist(self)

Add a comment
Know the answer?
Add Answer to:
Python 1 import matplotlib.pyplot as plt 2 import numpy as np 3 4 abscissa = np.arange(20) 5 plt....
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • PYTHON import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.linear_model import...

    PYTHON import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split Our goal is to create a linear regression model to estimate values of ln_price using ln_carat as the only feature. We will now prepare the feature and label arrays. "carat"   "cut" "color"   "clarity"   "depth"   "table"   "price"   "x"   "y"   "z" "1" 0.23   "Ideal" "E" "SI2" 61.5 55 326   3.95   3.98   2.43 "2" 0.21   "Premium" "E" "SI1"...

  • Urgent! Consider the following code for the point class studied in week 2: Import math class...

    Urgent! Consider the following code for the point class studied in week 2: Import math class Point: #static attribute _count = 0 # to count how many points we have created so far # initialization method def _init__(self, x = 0, y = 0): #default arguments technique self._x = x self._y=y Point_count += 1 #updating the point count #updating the Point count #getters def getX(self): return self._x def getY(self): return self._y def printPoint(self): return " + str(self._x)+ ' ' +...

  • 11p Python Language Read the following code for oofraction. import oofraction class OOFraction: def main(): fl...

    11p Python Language Read the following code for oofraction. import oofraction class OOFraction: def main(): fl = oofraction.o0Fraction( 2, 5) f2 = oofraction.o0Fraction ( 1, 3) f3 = f1 + f2 print (str(3)) main() def __init__(self, Num, Den): self.mNum = Num self.mDen = Den return def_add_(self,other): num = self.mNumother.mDen + other.mNum*self.mDen den = self.mDen*other.mDen f = OOFraction(num,den) return f 1. Write the output below. def_str_(self): s = str( self.mNum )+"/" + str( self.mDen) returns 2. Write a class called wholeNum...

  • Using python Here is the code import turtle def draw_triangle(vertex, length, k): ''' Draw a ...

    Using python Here is the code import turtle def draw_triangle(vertex, length, k): ''' Draw a triangle at depth k given the bottom vertex.    vertex: a tuple (x,y) that gives the coordinates of the bottom vertex. When k=0, vertex is the left bottom vertex for the outside triangle. length: the length of the original outside triangle (the biggest one). k: the depth of the input triangle. As k increases by 1, the triangles shrink to a smaller size. When k=0, the...

  • In Python import numpy as np Given the array a = np.array([[1, 2, 3], [10, 20,...

    In Python import numpy as np Given the array a = np.array([[1, 2, 3], [10, 20, 30], [100, 200, 300]]), compute and print the sums over all rows (should give [6, 60, 600]) the sums over all columns (the sum of he first column is 111) the maximum of the array the maxima over all rows the mean of the sub-array formed by omitting the first row and column the products over the first two columns (hint: look for an...

  • uestion 3 (1 point) the production function is f(x1, x2) = x1/21x1/22. If the price of...

    uestion 3 (1 point) the production function is f(x1, x2) = x1/21x1/22. If the price of factor 1 is $10 and the price of factor 2 is $20, in what proportions should the firm use factors 1 and 2 if it wants to maximize profits? Question 3 options: We can’t tell without knowing the price of output. x1 = 2x2. x1 = 0.50x2. x1 = x2. x1 = 20x2. Question 4 (1 point) A firm has the production function f(X,...

  • I need to complete the code by implementing the min function and the alpha betta pruning...

    I need to complete the code by implementing the min function and the alpha betta pruning in order to complete the tic tac toe game using pything. code: # -*- coding: utf-8 -*- """ Created on: @author: """ import random from collections import namedtuple GameState = namedtuple('GameState', 'to_move, utility, board, moves') infinity = float('inf') game_result = { 1:"Player 1 Wins", -1:"Player 2 Wins", 0:"It is a Tie" } class Game: """To create a game, subclass this class and implement actions,...

  • Intro to Python: Q1: Bonnie is writing a Python program for her math class so she can check her answers quickly. She is...

    Intro to Python: Q1: Bonnie is writing a Python program for her math class so she can check her answers quickly. She is having some difficulties, however, because when she enters values like 3.5 or 2.71 her program throws an error. She has heard of your expertise in Python and asks for your help. What error is being thrown and how can she fix the program to accept values like 3.5 or 2.71? from math import sgrt def distance (coorl,...

  • Please answer python questions? class ItemPack ): 21 def-init--(self): self.--storage=[] self. _.jump -1 self. _.mid-self. ..jump...

    Please answer python questions? class ItemPack ): 21 def-init--(self): self.--storage=[] self. _.jump -1 self. _.mid-self. ..jump def __iter.(self) self._.mid-int (len (self..storage)-1)/2.0) self. _.jump 0 return (self def __next..(self): 10 ind self .-_aid+self.--jump if ind<0 or ind >=len (self.--storage): 12 13 14 15 raise StopIteration O vToRet self.--storage [ind] if self.--jump <=0 : self.--Jump 1-self.--Jump - else return (vToRet) self..storage.append (item) return (len(self.--storage)=#0) 17 self.--jump*=-1 19 20def stuff (self, item) 21 22def isEmpty (self) 24def unpack (self): if len (self. .storage)0return...

  • using Python --- from typing import List THREE_BY_THREE = [[1, 2, 1], [4, 6, 5], [7,...

    using Python --- from typing import List THREE_BY_THREE = [[1, 2, 1], [4, 6, 5], [7, 8, 9]] FOUR_BY_FOUR = [[1, 2, 6, 5], [4, 5, 3, 2], [7, 9, 8, 1], [1, 2, 1, 4]] UNIQUE_3X3 = [[1, 2, 3], [9, 8, 7], [4, 5, 6]] UNIQUE_4X4 = [[10, 2, 3, 30], [9, 8, 7, 11], [4, 5, 6, 12], [13, 14, 15, 16]] def find_peak(elevation_map: List[List[int]]) -> List[int]: """Return the cell that is the highest point in the...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT