Concat method in Class

Question:

I am working through the following exercise: I am implementing a class that represents sorted lists of basic types.

Currently:

class SortedList():
    def __init__(self, input_list):
        self.input_list= input_list
    
    def add(self,value):
        self.input_list.append(value)
        return self.input_list

    def concat(self):
        return 

    def __repr__(self):
        self.input_list.sort()
        return str(self.input_list)

I make the following calls:

l1= SortedList(['z','l','a'])
print(l1)
l1.add('b')
print(l1)
l2= SortedList(['q','g'])
l3= l1.cocat(l2)
print(l3)

Everything behaves as expected until the l3 definition, since unsure how to define this type of function x.function(y) within a class.

The desired output from the last print statement is [‘a’,’b’,’g’,’l’,’q’,’z’]

Asked By: daniel stafford

||

Answers:

You can use the + operator on lists which extends a list with another list, and then return a new instance of SortedList when concat() is called.

class SortedList:
    def __init__(self, input_list):
        self.input_list = sorted(input_list)

    def add(self, value):
        self.input_list.append(value)
        self.input_list.sort()
        return self.input_list

    def concat(self, other):
        merged = self.input_list + other.input_list
        return SortedList(merged)

    def __repr__(self):
        return str(self.input_list)


l1 = SortedList(["z", "l", "a"])
print(l1)
# ['a', 'l', 'z']
print(l1.add("b"))
# ['a', 'b', 'l', 'z']
l2 = SortedList(["q", "g"])
l3 = l1.concat(l2)
print(l3)
# ['a', 'b', 'g', 'l', 'q', 'z']
Answered By: MagicalCornFlake
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.