anybody familiar with python

User Generated

Zrqhfnlajn

Computer Science

Description

please follow the instructions in the file

can you please make 2 different versions please i will pay 35$ per version

Unformatted Attachment Preview

CS 112 – Project 6 Classes, Exceptions Due Date: SUNDAY, May 7th, 11:59pm Note: no late submissions allowed on this project! Make the deadline, plan ahead. Please read the "Notes" section before writing any code! The purpose of this assignment is to explore classes and exceptions. We will be creating classes to represent books, patrons, and libraries, and then implementing some methods to capture the interactions available between them. • You will turn in a single python file following our naming convention (example: gmason76_2XX_P6.py) • Similar to previous projects, include your name, G#, Lecture/Lab sections, and any extra comments we ought to know, as a comment at the top of your file. • If you have questions, use Piazza (and professor/TA office hours) to obtain assistance. • Remember, do not publicly post code for assignments on the forum! Ask a general question in public, or ask a private question (addressed to all "instructors") when you're asking about your particular code. Also please have a specific question; instead of "my code doesn't work, please help", we need to see something like "I'm having trouble when I add that particular line, what am I misunderstanding?". If you are unsure whether a question may be public or not, just mark it as private to be sure. We can change a post to public afterwards if it could have been public. Background Classes allow us to define new types for Python. We can first think of a class as defining a new container – instead of a list, tuple, set, or dictionary, we can have our own collection of values, each with a chosen name. We can then read out a value or update a value, much like reading or replacing the values in a list or dictionary. But we can also put methods in a class definition, giving us a way to specify the exact ways we should interact with values of this new type. Once we have created a class definition, we can create as many objects of the new type as we want and use them in our programs. We can create entirely new types during the design phase of writing a program. This enables us to think in terms of types (and instances of types) that better model what we see in the real world, instead of endlessly relying on lists or dictionaries (and having to remember exactly how we intended to use those things as proxies for the values we actually had in mind). Exceptions allow us to recover from unusual events – some unavoidable (user types in bad file name or bad input in general), some unexpected (such as IndexErrors when stepping through a list). Without exceptions, we tend to program in an "ask permission, then attempt" style of calculation. But using exceptions, we can instead program in a "try it first, beg for forgiveness" approach by writing code that specifies how to recover from exceptions that we allowed to occur. What's Allowed? We've finally learned a substantial bit of programming! On this assignment, don't import anything except math; other than that you should be able to use any built-ins that you want; the project focuses on class structure, so there's not likely to be things that would make for any shortcuts. 1 Procedure Complete the class definitions as described; you can test your code with the included testing file: • Invoke it as with prior assignments: python3 tester6p.py yourcode.py • You can also test individual parts of the code, but note that you either want to type a class name or the name of a batch of test cases. You can either use the class name to test __init__, __str__, and __eq__ (any 'basic functionality' tests), or the other method names from Train, City, and Journey classes: python3 tester6p.py yourcode.py Train python3 tester6p.py yourcode.py unload_passengers python3 tester6p.py yourcode.py Train City Journey add_destination … o In addition to method and class names, these three names can be used to test exception behavior of relevant methods/classes: unload_passengers_exception, load_passengers_exception, and journey_type_error. • You can also run your code in interactive mode: python3 –i yourcode.py Scenario You will create world with cities, trains, and exciting journeys! This will require some proscribed class definitions. Create all the classes as defined below, all in your single .py file. Some of the classes build upon each other – this is an example of aggregation. Many of the methods required below are very regular – after you've seen one __init__ method on this program, you've sort of seen them all. While there might be a bit more typing than usual, the amount of mental work to "solve the puzzle" should be a bit minimal once you get used to the patterns. Classes You will be writing four classes (Train, City, Journey, and TrainCapacityException). Make sure you understand what these represent and how they relate to each other before continuing. Train class: Instance variables: • name • max_passengers • num_passengers • speed_fps :: string :: int :: int :: int # the name of the train # the maximum number of passengers the train can transport # the number of passengers currently on the train # how fast the train travels (in feet per second) Methods: • __init__(self, name, max_passengers, speed_fps) :: constructor, initializes all instance variables, num_passengers should default to 0 when a train is created with the constructor. o Assumptions: § speed_fps and max_passengers will always be a non-negative number § name will be a non-empty string 2 • __str__(self) :: returns string representation with this format: "Train named Orient Express with 5 passengers will travel at 10.20mph" o Notes: § The quotes in the example are just our string boundaries! The first character in the above example is T. § This method reports num_passengers (NOT max_passengers). § Train speed is converted to mile per hour and always presented with 2 digits after the decimal point. • time_to_travel(self, distance_feet) :: to travel distance_feet (distance in feet). Returns how long (in whole seconds) this train will take o Notes and Assumptions: § This always returns an integer – you could use integer division (//) or normal division followed by int() conversion to truncate the fractional part. § You can assume that distance_feet is always a non-negative integer. • load_passengers(self, num_people) :: Attempts to put num_people onto the train and update num_passengers. If the number of people supplied would not fit on the train, raise a TrainCapacityException and do not change the number of passengers currently on the train. [You may imagine this as “the passengers get into a fight and no one is allowed on the train”.] o Note and Assumptions: § You can assume that num_people is always a non-negative integer. § When raising the exception, the number to raise is the number of people that cannot fit on the train (not the number of people that try to board). § This function should return None. Remember: None is the default return if you don’t return anything! You don’t need to explicitly return None. • :: Attempts to remove num_people from the train. If the number of people supplied is larger than the number of people on the train currently, raise a TrainCapacityException and do not change the number of passengers currently on the train. [You may imagine this as “the passengers are so confused by the request that they just stay where they are looking confused”.] o Note and Assumptions: § You can assume that num_people is always a non-negative integer. § When raising the exception, the number to raise is the number of people that cannot unload, not the number of people that try to exit the train. § This function should return None. Remember: None is the default return if you don’t return anything! You don’t need to explicitly return None. unload_passengers(self, num_people) TrainCapacityException class: By specifying the parent class Exception as in the example below, objects (values) of this class can be raised and caught. class TrainCapacityException(Exception): Instance variables: • • number issue :: int :: string # # # # how many people can’t fit or be unloaded from the train should be either "full" or "empty" "full" indicates that the train was full "empty" indicate the error was due to the train being empty 3 Methods: • __init__(self, number, issue="full") :: constructor; instantiates all instance variables. You can assume all incoming arguments are good and no need to perform any checking. • :: returns string representation matching this format (based on number and issue): o '5 passengers cannot be loaded because the train is full!' o '5 passengers cannot be unloaded because the train is empty!' __str__(self) City class: Instance variables: • name • loc_x • loc_y • stop_time :: string :: int :: int :: int # # # # the the the how name of the city city’s x location (in an x-y-coordinate system) city’s y location (in an x-y-coordinate system) long (in number of seconds) trains stop in this city Methods: • __init__(self, name, loc_x, loc_y, stop_time) :: constructor, initializes all instance variables. o Assumption: All incoming arguments are good; there is no need to perform any checking. • :: returns string representation with this format (note, the quotes in the example are just our quote boundaries! The first character in this example string is N): __str__(self) "New York (0,3). Exchange time: 5.00 minutes" o Notes: § The (0,3) in the example above are the coordinates of the city. § Stop time is converted to number of minutes with 2 digits after the decimal point. :: Override the == method for City objects; returns True or False. Cities should be “equal” to each other if they are at the same location (loc_x and loc_y), regardless of their name or stop time. For example, City("New York", 0, 0, 0) and City("The Big Apple", 0, 0, 10) would be the same since they are physically located in the same location. • __eq__(self, other) • distance_to_city(self, city) :: Returns the distance between to cities (based on their x and y locations) as a float (no truncating). Remember: a2 + b2 = c2! Journey class: Instance variables: • train • destinations • start_time :: Train :: list of City objects :: int # # # # the the the (in train making the journey cities the train will visit, in order time the train will begin its journey st seconds since January 1 , 1970) Note: Why Thursday, Jan. 1st 1970? See: https://en.wikipedia.org/wiki/Unix_time 4 Methods: • __init__(self, train, destinations=None, start_time=0) :: constructor, initializes all instance variables. When no list of Cities is supplied, this creates an empty list as destinations. This should raise a TypeError if (a) train is not of type Train, (b) destinations is not of type list, or (c) destinations contains anything other than instances of City. o Hint: Use the type() function to determine the type! (This was introduced near the beginning of the semester.) • __str__(self) :: returns string representation with this format (when printed out): Journey with 3 stops: Philadelphia (0,0). Exchange time: 30.00 minutes New York (0,22). Exchange time: 10.00 minutes Boston (22,22). Exchange time: 5.00 minutes Train Information: Train named Orient Express with 5 passengers will travel at 15.00mph o Notes: § Each city in the destinations is presented on a separate line, starting with a tab § The train information is the last line and ends with a newline o Hints: § You should reuse the string formatting for Train and City objects instead of defining them again! § Look at the sample run (and tester file) for more examples! :: Appends a city to the list of destinations and returns None. Assumption: You may assume city is an instance of City. • add_destination(self, city) • city_in_journey(self, city) • check_journey_includes(self, start_city, dest_city) :: Check if the journey will include travel from the start_city to the dest_city. Stops are acceptable in between the two cities. Returns a :: Determines if a city is one of the destinations in the journey. Returns a boolean. Assumption: You may assume city is an instance of City. boolean. o Hints and Assumptions: § There are many ways to solve this problem, but the list’s index() method might be helpful here. You now know how to handle the exceptions it might raise! § You may assume cities are instances of City. :: Returns the total distance traveled (in feet as a float). • total_journey_distance(self) • city_arrival_time(self, city) :: Returns the time at which the train will arrive at a given city. It returns an integer -- whole seconds since January 1st, 1970 (similar to how we specify start_time of the journey). Returns None if city is not included in journey. If the city is visited more than once on the journey, the first time the city is visited should be returned. You may assume city is an instance of City. The arrival time can be computed by: Stop Time at Start City Start City arrival time (start_time) Journey Time to Second City Start City departure time Stop Time at Second City 2nd City arrival time 5 2nd City departure time … Arrival at City of Interest :: Returns the time at which the train will leave the given city. It returns an integer -- whole seconds since January 1st, 1970. Returns None if city is not included in journey. If the city is visited more than once on the journey, the last time the train leaves the city should be returned. You may assume city is an instance of City. • city_departure_time(self, city) • total_journey_time(self) • all_passengers_accommodated(self, unload_list, load_list) :: Returns the total time taken on the journey (in seconds). This is the departure time of the last city minus the start time of the journey. :: Given a list with the number of passengers unloading at each city, and a list of the number of passengers boarding the train at each city, determine if all passengers can be accommodated (i.e. they will all be able to board / leave as indicated in the lists). For example: Unload List: [0,1,2], Load List: [1,2,0] #at the first city, unload: 0 passengers will try to exit the train load: 1 passenger will try to board the train #at the second city, unload: 1 passenger will try to exit the train load: 2 passengers will try to board the train #at the third city, unload: 2 passengers will try to exit the train load: 0 passengers will try to board the train o Notes: § You must ask the train of the journey to load_passengers or unload_passengers. This will adjust the num_passengers on the train. § Exceptions might be raised via the code from the Train class; you must handle these exceptions and return the required boolean as part of your exception handling. § The train may or may not start with passengers already on the train at the first city. § At the end, the number of people on the train may be non-zero. o Assumptions: § The length of unload_list and load_list will be the same as each other and both will be equal to the size of the destinations list for the journey. § The unload_list and load_list will never contain invalid values (such as negative numbers), but they might contain 0s. Grading Rubric Code passes shared tests: 95% Well-documented/submitted: 10% --------------------------------TOTAL: 105% extra credit is baked in! No globals allowed – you'll be penalized if you use them! There are five extra points available rather than a specific set of extra credit points. Earn as many as you can from anywhere and get a good score to finish the semester strong! 6 Notes • You are encouraged to add any extra functions, methods, or classes that you want! As long as you are passing the provided test cases. • When testing your code interactively (-i flag), you might want to create a Journey that already has specific trains and cities. You can borrow definitions from our testing file as you see fit. Sample Session Some of the functionality is exhibited below. You might gain understanding by inspecting the tester file's contents, too. >>> t = Train("train 1", 10, 22) #22 fps = 15 mph >>> t.name 'train 1' >>> t.time_to_travel(2200) # Time to travel 2200ft 100 >>> str(t) 'Train named train 1 with 0 passengers will travel at 15.00mph' >>> >>> for i in range(0,10): ... try: ... t.load_passengers(i) ... print("\tLoaded " + str(i) + " passengers, train has " + str(t.num_passengers)) ... except TrainCapacityException as e: ... print(e) ... Loaded 0 passengers, train has 0 Loaded 1 passengers, train has 1 Loaded 2 passengers, train has 3 Loaded 3 passengers, train has 6 Loaded 4 passengers, train has 10 5 passengers cannot be loaded because the train is full! 6 passengers cannot be loaded because the train is full! 7 passengers cannot be loaded because the train is full! 8 passengers cannot be loaded because the train is full! 9 passengers cannot be loaded because the train is full! >>> for i in range(0,10): ... try: ... t.unload_passengers(i) ... print("\tUnloaded " + str(i) + " passengers, train has " + str(t.num_passengers)) ... except TrainCapacityException as e: ... print(e) ... Unloaded 0 passengers, train has 10 Unloaded 1 passengers, train has 9 Unloaded 2 passengers, train has 7 Unloaded 3 passengers, train has 4 Unloaded 4 passengers, train has 0 5 passengers cannot be unloaded because the train is empty! 6 passengers cannot be unloaded because the train is empty! 7 passengers cannot be unloaded because the train is empty! 8 passengers cannot be unloaded because the train is empty! 9 passengers cannot be unloaded because the train is empty! >>> t.load_passengers(5) >>> str(t) 'Train named train 1 with 5 passengers will travel at 15.00mph' >>> >>> c1 = City("city 1", 0, 0, 30*60) #stop time is 30 minutes >>> str(c1) 'city 1 (0,0). Exchange time: 30.00 minutes' >>> c1.name 'city 1' >>> >>> c2 = City("city 2", 0, (22), 10*60) #stop time is 10 minutes >>> str(c2) 'city 2 (0,22). Exchange time: 10.00 minutes' >>> >>> c3 = City("city 3", (22), (22), 5*60) #stop time is 5 minutes >>> str(c3) 'city 3 (22,22). Exchange time: 5.00 minutes' >>> >>> (c1 == c2) False >>> c1.distance_to_city(c2) 22.0 >>> c2.distance_to_city(c3) 22.0 >>> c3.distance_to_city(c1) 31.11269837220809 >>> >>> j = Journey(t, [c1,c2], 60) >>> j.add_destination(c3) >>> str(j) 'Journey with 3 stops:\n\tcity 1 (0,0). Exchange time: 30.00 minutes\n\tcity 2 ( 0,22). Exchange time: 10.00 minutes\n\tcity 3 (22,22). Exchange time: 5.00 minut es\nTrain Information: Train named train 1 with 5 passengers will travel at 15.0 0mph\n' >>> >>> j.city_arrival_time(c1) 60 >>> j.city_arrival_time(c2) 1861 >>> j.city_arrival_time(c3) 2462 >>> >>> j.all_passengers_accommodated((0,5,5),(5,5,5)) True >>> j.all_passengers_accommodated((0,5,5),(5,100,5)) False >>> j.all_passengers_accommodated((0,100,5),(5,5,5)) False >>> >>> j.check_journey_includes(c1,c3) True >>> j.check_journey_includes(c3,c1) False >>> j.check_journey_includes(c3,City("city 3", 100, 100, 5)) False >>> 7 Final Notes You should always test your code not only with the provided testing script, but also by directly calling your code, to explore what's happening. If you store sample values to variables after all the definitions, you can use them in these interactive calls. This is also how you might test your code out in the visualizer, which we highly recommend. Just be sure to remove them before turning in your work – they are globals, which are not allowed in your final submission. Consider the file below on the left, named shouter.py, which you can run as shown below on the right using interactive mode (-i). def shout(msg): print(msg.upper()) demo$ python3 –i shouter.py >>> shout("i wrote this") 'I WROTE THIS' >>> shout(mystring1) 'HELLO' >>> shout(mystring2) 'ANOTHER ONE' mystring1 = "hello" mystring2 = "another one" You will not earn test case points if you hard-code the answers. Your program should work for all possible inputs, not just the provided test cases. If you notice that one test case calls something(3), and you write the following to pass that particular test case, you'd be hardcoding. We reserve the right to deduct any points inappropriately earned through hardcoding. def something(x): if x==3: # hard-coding example return 8 # a memorized answer that avoids actually calculating the number directly Notice how it's not actually calculating, it's merely regurgitating a memorized answer. Doing this for all used test cases might make you feel like you've completed the program, but there are really unlimited numbers of test cases; hardcoded programs only work on the inputs that were hardcoded. Nobody learns, and the program isn't really that useful. When it's a true corner case (often around zero, empty lists, etc), we might need to list a direct response for those situations; this is not hardcoding. Only when it's obvious you're focusing on the given test cases is this really an issue. Reminders on Turning It In: No late work is accepted for this last project, regardless of token usage. You can turn in your code as many times as you want; we only grade the last submission that is
Purchase answer to see full attachment
User generated content is uploaded by users for the purposes of learning and should be used following Studypool's honor code & terms of service.

Explanation & Answer

Inside go...


Anonymous
I was struggling with this subject, and this helped me a ton!

Studypool
4.7
Trustpilot
4.5
Sitejabber
4.4

Related Tags