Question

python program A line segment in one dimension is defined by an ordered pair of coordinates...

python program

A line segment in one dimension is defined by an ordered pair of coordinates representing the left and right boundaries of the segment. Write a class Segment that implements the interface below, which includes testing whether a point is in a segment, and whether two segments overlap. Note that the constructor should raise an appropriate exception if it receives invalid input (left end is on the right of the right end). • __init__(): constructor that takes one or two arguments to build the segment. If only one value is given, it is assumed to be the coordinate of the right end, and the left end defaults to zero. Constructor raises an exception if left end is greater than right. • left(): returns coordinate of the left boundary • right(): returns coordinate of the right boundary • mid_point(): returns coordinate of the midpoint of the segment • contains(): takes a double argument x and returns a boolean indicating whether x is in the segment • overlaps(): takes a segment argument seg and returns a boolean indicating whether this segment and seg overlap • __lt__(): a less than method (<) that compares the midpoints of the segments • __str__(): returns a string representation of the segment (of the form [x0 – x1]) You should consider line segments to exclude the left endpoint x0 but include the right endpoint x1. The arguments to the constructor are ordered so that Segment(x0, x1) represents all points on the line in the half-closed interval (x0 x1]. Your code should be in a file called Segment.py, and should include a function that tests the methods of the Segment class. You have to think about and write an appropriate set of tests.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

thanks for the question, here is the complete Segment class in python, I have written some of the test cases, you need to write some of the -ve test cases.

=========================================================================================

class Segment():

    def __init__(self,right,left=0):
        if left>right:
            raise ValueError('Left coordinate value is greater than right coordinate value')
        self.right=right
        self.left=left

    def left(self):
        return self.left

    def right(self):
        return self.right

    def mid_point(self):
        return (self.left + self.right)/2

    def contains(self, x):
        return self.left<=x and x<=self.right

    def overlaps(self,seg):
        if self.left<seg.left and seg.left <self.right:
            return True
        elif self.left<seg.right and seg.right <self.right:
            return True
        else:
            return False

    def __lt__(self, other):
        return self.mid_point()<other.mid_point()

    def __str__(self):
        return '[{0} {1}]'.format(self.left,self.right)



def main():
    segment=Segment(9)
    print('Print Object ',segment)
    line =Segment(9,2)
    print('Is Segment<Line? ',segment<line)
    print(segment.mid_point(),line.mid_point())
    print('Does they Overlap? ',segment.overlaps(line))


main()

================================================================================================
Add a comment
Know the answer?
Add Answer to:
python program A line segment in one dimension is defined by an ordered pair of coordinates...
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
  • 1. In IntelliJ create a new project called F1_2 2. In the Project window create a...

    1. In IntelliJ create a new project called F1_2 2. In the Project window create a new Java package called F1_2. This can be done by right clicking on src and going to New ! Package. 3. In package lab1 2 create a class called Rectangle. This can be done by right clicking on the package and going to New ! Java Class 4. At the beginning of Rectangle.java add the line package lab1 2; 5. In Rectangle.java create a...

  • Must be in Java. Show proper reasoning with step by step process. Comment on the code...

    Must be in Java. Show proper reasoning with step by step process. Comment on the code please and show proper indentation. Use simplicity. Must match the exact Output. CODE GIVEN: LineSegment.java LineSegmentTest.java Point.java public class Point { private double x, y; // x and y coordinates of point /** * Creates an instance of Point with the provided coordinates * @param inX the x coordinate * @param inY the y coordinate */ public Point (double inX, double inY) { this.x...

  • Comment your code. At the top of the program include your name, a brief description of...

    Comment your code. At the top of the program include your name, a brief description of the program and what it does and the due date. The program must be written in Java and submitted via D2L. The code matches the class diagram given above. The code uses Inheritance. In the following, you are given code for two classes: Coin and TestCoin. You study these classes first and try to understand the meaning of every line. You can cut and...

  • In C++, develop a class that supports array rotation. Rotating an array is an operation where...

    In C++, develop a class that supports array rotation. Rotating an array is an operation where you shift all elements of the array some number of positions left or right, and elements that are shifted off of the left or right end of the array "wrap around" to the right or left end, respectively. For example, if we rotate the array [1, 2, 3, 4, 5] to the right by 1, we get the array [5, 1, 2, 3, 4]....

  • A java program for this question please! Recursion: A word is considered elfish if it contains...

    A java program for this question please! Recursion: A word is considered elfish if it contains the letters: e, l, and f in it, in any order. For example, we would say that the following words are elfish: whiteleaf, tasteful, unfriendly, and waffles, because they each contain those letters. Write a recursive method called elfish(), that, given a word, tells us whether or not that word is elfish. The signature of the method should be: public static boolean elfish(String word)...

  • I really need help with this python programming assignment Program Requirements For part 2, i need...

    I really need help with this python programming assignment Program Requirements For part 2, i need the following functions • get floats(): It take a single integer argument and returns a list of floats. where it was something like this def get_floats(n):   lst = []   for i in range(1,n+1):     val = float(input('Enter float '+str(i)+': '))     lst.append(val)   return lst • summer(): This non-void function takes a single list argument, and returns the sum of the list. However, it does not use...

  • programming language: C++ *Include Line Documenatations* Overview For this assignment, write a program that will simulate...

    programming language: C++ *Include Line Documenatations* Overview For this assignment, write a program that will simulate a game of Roulette. Roulette is a casino game of chance where a player may choose to place bets on either a single number, the colors red or black, or whether a number is even or odd. (Note: bets may also be placed on a range of numbers, but we will not cover that situation in this program.) A winning number and color is...

  • DIRECTIONS FOR THE WHOLE PROJECT BELOW BigInt class The purpose of the BigInt class is to...

    DIRECTIONS FOR THE WHOLE PROJECT BELOW BigInt class The purpose of the BigInt class is to solve the problem using short methods that work together to solve the operations of add, subtract multiply and divide.   A constructor can call a method called setSignAndRemoveItIfItIsThere(). It receives the string that was sent to the constructor and sets a boolean variable positive to true or false and then returns a string without the sign that can then be processed by the constructor to...

  • In this lab you will write a spell check program. The program has two input files:...

    In this lab you will write a spell check program. The program has two input files: one is the dictionary (a list of valid words) and the other is the document to be spellchecked. The program will read in the words for the dictionary, then will read the document and check whether each word is found in the dictionary. If not, the user will be prompted to leave the word as is or type in a replacement word and add...

  • This is the contents of Lab11.java import java.util.Scanner; import java.io.*; public class Lab11 { public static...

    This is the contents of Lab11.java import java.util.Scanner; import java.io.*; public class Lab11 { public static void main(String args[]) throws IOException { Scanner inFile = new Scanner(new File(args[0])); Scanner keyboard = new Scanner(System.in);    TwoDArray array = new TwoDArray(inFile); inFile.close(); int numRows = array.getNumRows(); int numCols = array.getNumCols(); int choice;    do { System.out.println(); System.out.println("\t1. Find the number of rows in the 2D array"); System.out.println("\t2. Find the number of columns in the 2D array"); System.out.println("\t3. Find the sum of elements...

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