File Edit Format Run Options Window Help # defines the city class description :
ID: 3730142 • Letter: F
Question
File Edit Format Run Options Window Help # defines the city class description : # -each "City" object has: 1. name 2 position (x, ) l. be created . describe itself 3. calculate distance between itself and another city # -each "City" object can: import math # for calculating distance chass City: # Class definition t constructs city det --init_ (self, name in, xin, y-in); self.namename in self.xint(x in) self.yint(y in) def -str-(self) : recurn "City Name # Describes city self.name V "Inx-coordinate: "self.x "Inx-coordinate: selt.y pass # remember to delete it def distance (sels, other) distX-math.pow (self.x - other.x, 2) # Euclidean distance for rX) distY-math . pow(self.y-other. y, 2) # Euclidean distance for (y) dist ma tn.sqrt (self.x + self.y) pzint dist Total distance between cities # testing section # Used to define special va riables. name main cityone City("La Hesa", 100, 10) cityTwo-City("Carlsbad", 100, 80) print "cesting..." tor i in range (1,5): # This will allow you to enter 4 cities. cityname raw input ("Enter the name of the City:) x_coordinate raw input ("Enter the X-Coordinate of the city: ) y_coordinate raw input ("Enter the Y-Coordinate of the cicy: ") self City) self.set name in (cityname) self.setx in(x coordinate) self.set_v in (y_coordinate) # print the cities (their descriptions) # now calculate the distance between cityone and cityTwo # using the distance method t diaplay the result in some meaningtul way (i.e using some s descriptive sentence) Ln: 16 Col 26Explanation / Answer
Constructors defined by __init__() are used for auto initialization when objects of the class are created. So inside for loop once use has entered name and x-y cordinates, just create an object as:
city1 = City(cityname,x_coordinate, y_coordinate)
Another way could be create a list for objects before for loop and then add objects to the list as:
test_objects = []
for i in range(1,5):
# Get user input
#now initialize objects & add them to the list
test_objects.append( City(cityname,x_coordinate, y_coordinate)))
- To print details of the cities:
for i in range(0,4):
print test_objects[i]
- Calculate ditance between as below(you can add some kind of tabluar form if you want):
for i in range(0,4):
for i in range(i+1,4):
print "Distance between city" + (i+1) + "and city" + (j+1) + "is"
test_objects[i].distance(test_objects[j]
Hope this helps somewhat :)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.