Dec-09-2018, 10:44 PM
class SortedList: def __init__(self): """ Constructor: build an empty sorted list """ self.nums = list() def add_value(self, value): """ Add a new value to the sorted list: should insert the new value to the right index if there are existing values in the list. """ if len(self.nums) == 0: self.nums.append(value) else: if value > max(self.nums): #append if value is greater than number being inserted self.nums.append(value) elif value <= max(self.nums): #insert the vlue if value is less than value self.nums.insert(0, value) def __str__(self): """ Return a string with all the values in the list """ return str(self.nums) def remove_value(self,value): """ Remove a given value from the list. If there is no such value, return a ValueError: "No such value" Otherwise, remove one and only one instance of the specified value """ if value not in self.nums: raise ValueError("No such value") else: self.nums.remove(value) # Testing code: build an empty sorted list and add values. my_sorted_list = SortedList() my_sorted_list.add_value(1) my_sorted_list.add_value(2) my_sorted_list.add_value(0) my_sorted_list.add_value(100) my_sorted_list.add_value(-100) my_sorted_list.add_value(50) # print the items in the list, the values should be sorted: [-100, 0, 1, 2, 50, 100] print(my_sorted_list) # try to remove two values, the 2nd value to remove will cause an error try: my_sorted_list.remove_value(2) my_sorted_list.remove_value(22) except ValueError as e: print(e) print(my_sorted_list)the value 50 is not sorting correctly but all of the other values are sorting correctly