0

Suppose I want to send a list in python and I will have a MyList class that will have 3 constructors. sending an empty list would return nothing, sending a list would convert it into a linked list and sending a linked list will copy its item and make another linkedlist from it

Task 1: i) Create a Node class that will hold two fields i.e an integer element and a reference to the next Node. ii) Create a Linked list Abstract Data Type (ADT)named MyList.The elements in the list are Nodes consisting of an integer type key (all keys are unique) and a reference to the next node.

Task 2: Constructors:(3)

MyList ( ) Pre-condition: None. Post-condition: This is the default constructor of MyList class. This constructor creates an empty list.

b. MyList (int [] a) or Myst(a) Pre-condition: Array cannot be empty. Post-condition: This is the default constructor of MyList class. This constructor creates a list from an array.

c. MyList (MyList a) or MyList(a)

Pre-condition: List cannot be empty. Post-condition: This is the default constructor of MyList class. This constructor creates a list from another list.

  • 2
    This sounds like you're taking a Java course that was awkwardly converted to a Python class without accounting for the differences between the two languages. If so, a lot of the stuff you're learning won't actually apply to Python, or won't be a good idea in Python. – user2357112 Mar 18 '21 at 08:13
  • 2
    Python does not have method overloading. – juanpa.arrivillaga Mar 18 '21 at 08:13

1 Answers1

0

For Task 2 : You can try something like this, by checking the input in the constructor of your class:

class MyList():
    def __init__(self, a=None):
        self.list = []
        if a is None:
            return
        elif isinstance(a, list):
            if len(a) == 0:
                raise ValueError('List cannot be empty.')
            else:
                self.list = a
            return
        elif isinstance(a, MyList):
            if len(a.list) == 0:
                raise ValueError('List cannot be empty.')
            else:
                self.list = a.list.copy()
        else:
            raise TypeError('Unkonw type for a')
Oily
  • 538
  • 3
  • 11
  • can you tell what the (a.list.copy) thing does? –  Mar 18 '21 at 16:11
  • It is basically copying the internal list of the MyList object a. If you don't put .copy(), you would only do a shallow copy and when you change an object in a.list, it would also be changed in self.list . Check more about deep copy vs shallow copy. https://stackoverflow.com/questions/184710/what-is-the-difference-between-a-deep-copy-and-a-shallow-copy – Oily Mar 19 '21 at 08:37