There is a Location class
class Location(object):
def __init__(self, x, y):
self.x = x
self.y = y
def move(self, deltaX, deltaY):
return Location(self.x + deltaX, self.y + deltaY)
def getX(self):
return self.x
def getY(self):
return self.y
def dist_from(self, other):
xDist = self.x - other.x
yDist = self.y - other.y
return (xDist**2 + yDist**2)**0.5
def __eq__(self, other):
return (self.x == other.x and self.y == other.y)
def __str__(self):
return '<' + str(self.x) + ',' + str(self.y) + '>'
and a get_cars method which I wrote to retrieve data from the list (doesn't belong to LOcation class) according to the spec below:
def get_cars(self):
""" Returns a list of all cars on the parking. The list should contain
the string representation of the Location of a car. The list should
be sorted by the x coordinate of the location. """
result = ''
for i in sorted(self.car_loc_list, key=lambda Location: Location.x):
if self.car_loc_list[0] == i:
result += '\'' + str(i) + '\''
else:
result += ', ' + '\'' + str(i) + '\''
return '[' + result + ']'
self.car_loc_list is just a list which holds objects of Location class and they contain some coordinates(x,y) (unsorted):
for i in c.car_loc_list:
print(i)
<0,0>
<1,5>
<7,2>
<2,1>
<1,7>
<4,3>
The online grader examine my code in 2 ways:
print(c.get_cars())- OKprint(sorted(c.get_cars()))- NOT OK
When I follow the first way:
print(c.get_cars())
It prints out the next result sorted by X coordinate(1-st digit):
print(c.get_cars())
Out[539]: "['<0,0>', '<1,5>', '<1,7>', '<2,1>', '<4,3>', '<7,2>']"
It is also the result which I (and grader) expected to receive.
When I do print(sorted(c.get_cars)) I get:
print(sorted(c.get_cars()))
[' ', ' ', ' ', ' ', ' ', "'", "'", "'", "'", "'", "'", "'", "'", "'", "'", "'", "'", ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', '0', '0', '1', '1', '1', '2', '2', '3', '4', '5', '7', '7', '<', '<', '<', '<', '<', '<', '>', '>', '>', '>', '>', '>', '[', ']']
I stuck at this place. Also I understand that it somehow transforms my output to the string again and that is why I get such result. Is there any idea how to implement so that both solutions give the same result according to the spec above e.g ['<0,0>', '<1,5>', '<1,7>', '<2,1>', '<4,3>', '<7,2>'] ?
UPD Seems I didin't understand the next sentence:
The list should contain the string representation of the Location of a car.
sorted()on a list returns individual characters in sorted order.'<x,y>', so['<0,0>', '<1,5>', '<1,7>', '<2,1>', '<4,3>', '<7,2>'](note that there are no double quotes around that value).str(i)gives you that. Add those to a list.