Python Forum
Python - List - Int List
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python - List - Int List
#1
Question 
Hi, I'm new here and I don't speak English well, but I need a lot of help
I have difficult task:
Define an IntList () class whose objects will behave the same as objects of the list () class, except that they can only contain integers. When you try to insert (in any way) into such a list something other than an int value, the object throws an exception. As a parent class you can use list.

I don't know how to move with it and I didn't find anything on the internet, so I turn here
Reply
#2
Please:
  • Make an effort
  • post your code
  • Ask specific questions
Reply
#3
class IntList(list):
       def __init__(self):
          self.internal_list = []
       def append(self, elem):
           if not isinstance(elem, int):
               raise TypeError('x musi byt typu Integer')
           self.internal_list[len(self.internal_list):] = [elem]
       def getList(self):
           return self.internal_list
I have that, after a long time :D but I don't know if is the right implementation. Maybe I have problem with print some list. Should I add some others methods ?
Reply
#4
I think the hint "As a parent class you can use list." is a good hint. What other methods does list have?
Output:
>>> x = list() >>> print("\n".join(dir(x))) __add__ __class__ __contains__ __delattr__ __delitem__ __dir__ __doc__ __eq__ __format__ __ge__ __getattribute__ __getitem__ __gt__ __hash__ __iadd__ __imul__ __init__ __init_subclass__ __iter__ __le__ __len__ __lt__ __mul__ __ne__ __new__ __reduce__ __reduce_ex__ __repr__ __reversed__ __rmul__ __setattr__ __setitem__ __sizeof__ __str__ __subclasshook__ append clear copy count extend index insert pop remove reverse sort
Which of these many methods can put a value in the list? append() is a start, but there are others.
Reply
#5
class IntList(list):
    def __init__(self):
        super().__init__()
        self.list = []

    def __len__(self):
        return len(self.list)

    def append(self, elem):
        if not isinstance(elem, int):
            raise TypeError('x musí byť typu Integer')
        self.list[len(self.list):] = [elem]

    def insert(self, index, value):
        if not isinstance(value, int):
            raise TypeError('x musí byť typu Integer')
        self.list.insert(index, value)

    def get_list(self):
        return self.list

    def __str__(self):
        return f'{self.list}'

    def extend(self, listt):
        if not isinstance(listt, IntList):
            raise TypeError('Zoznam musí byť typu Integer')
        z = self.list
        y = listt.get_list()
        self.list = z + y
        print(self.list)
        return self.list

    @property
    def sort(self):
        x = len(self.list)
        for i in range(x):
            for j in range((i + 1), x):
                if self.list[i] > self.list[j]:
                    l1 = self.list[i]
                    self.list[i] = self.list[j]
                    self.list[j] = l1
        return self.list
Reply
#6
Your class that inherits from list should not have a list attribute. For example, instead of appending to a self.list, your IntList.append() method should look like this:
    def append(self, elem):
        if not isinstance(elem, int):
            raise TypeError('x musí byť typu Integer')
       super().append(elem)  # Call the append for my superclass
Making IntList a proper subclass of list will reduce how much code you need to write. For example, you don't need to write a sort. Sort does not add items to the list, so IntList can inherit the soft method from list. You don't need __init__(), __str_(), __len__(), or get_list() methods either.

I think you are still missing some methods that can add/set items in the the list. What about __setitem__() or __add__()? They looks suspicious.

I think your extend() method should allow types other than IntList. Check each value, as it is added.
Reply
#7
class IntList(list):
    def __init__(self):
        super().__init__()

    def append(self, elem):
        if not isinstance(elem, int):
            raise TypeError('x musí byť typu Integer')
        self[len(self):] = [elem]

    def insert(self, index, value):
        if not isinstance(value, int):
            raise TypeError('x musí byť typu Integer')
        zoznam = IntList()
        for x in range(len(self)):
            posledne = self[x]
            if x == index:
                zoznam.append(value)
            zoznam.append(posledne)
        self.clear()
        for x in range(len(zoznam)):
            self.append(zoznam[x])
        if (index >= len(self)):
            self.append(value)

    def get_list(self):
        return self

    def __str__(self):
        return self.__repr__()

    def extend(self, listt):
        if not isinstance(listt, IntList):
            raise TypeError('Zoznam musí byť typu Integer')
        for x in range(len(listt)):
            self.append(listt[x])
        return self
Hi, I hope, that this code is ok, because its working :D But I must override methods like __add__, __setitem__ and methods like that, I've tried find out what this methods do, but I don't know.
Reply
#8
This is not required:
    def __init__(self):
        super().__init__()
list.__init__() is automatically called if you your subclass does not have an __init__() method.

This is not required either. Just use the methods inherited from list.
    def __str__(self):
        return self.__repr__()
No need for this at all.
    def get_list(self):
        return self
This is overly complicated,
    def insert(self, index, value):
        if not isinstance(value, int):
            raise TypeError('x musí byť typu Integer')
        zoznam = IntList()
        for x in range(len(self)):
            posledne = self[x]
            if x == index:
                zoznam.append(value)
            zoznam.append(posledne)
        self.clear()
        for x in range(len(zoznam)):
            self.append(zoznam[x])
        if (index >= len(self)):
            self.append(value)
\
Raise an exception if value is a not a number, else call list.insert(value). Should a 3 lines.

And as mentioned before, in extend(listt) you should not force listt to be an IntList, or any kind of list for that matter. Should have to be iterable. According to the docs

Quote:list.extend(iterable)
Extend the list by appending all the items from the iterable. Equivalent to a[len(a):] = iterable.

Maybe a more concrete example:
class IntList(list):
    def __init__(self, values=None):
        """Provided so can initalize intlist with values"""
        super().__init__()
        if values:
            self.extend(values)

    def append(self, value):
        """Raise exception if bad value, else call superclass method"""
        if not isinstance(value, int):
            raise TypeError('Value must be int')
        super().append(value)

    def insert(self, index, value):
        """Raise exception if bad value, else call superclass method"""
        if not isinstance(value, int):
            raise TypeError('Value must be int')
        super().insert(index, value)

    def extend(self, iterable):
        """Raise exception if bad value, else call superclass method.  See a pattern?"""
        for value in iterable:
            if not isinstance(value, int):
                raise TypeError("All values must be int")
        super().extend(iterable)

x = IntList((1, 2, 3))
print(x)

x.append(4)
print(x)

try:
    x.insert(4, 'a')
except TypeError as msg:
    print(msg)

x[2] = "Oops"  # How you going to prevent this???
print(x)

x = x + [1.2, "three", {1:5}, [6, 7, 9]]  # Another problem?
print(x)
Output:
[1, 2, 3] [1, 2, 3, 4] Value must be int [1, 2, 'Oops', 4] [1, 2, 'Oops', 4, 1.2, 'three', {1: 5}, [6, 7, 9]]
Reply
#9
Ok, thank you, but I don't know what I have to do with __add__, __setitem__, nothing ?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  how to reverse a list and store in another list in python SuperNinja3I3 6 3,303 Aug-14-2022, 06:36 PM
Last Post: DeaD_EyE
  question on list in Python spalisetty06 1 2,058 Jun-30-2020, 09:03 AM
Last Post: pyzyx3qwerty
  Python list exercize ESTOUR 3 1,939 May-23-2020, 11:10 PM
Last Post: ESTOUR
  Python Adding +1 to a list item cointained in a dict ElReyZero 1 2,081 Apr-30-2020, 05:12 AM
Last Post: deanhystad
  Check if a list exists in given list of lists Daniel94 2 2,245 Apr-07-2020, 04:54 PM
Last Post: deanhystad
  list of strings to list of float undoredo 3 2,699 Feb-19-2020, 08:51 AM
Last Post: undoredo
  arrays sum list unsupported operand type(s) for +=: 'int' and 'list' DariusCG 7 4,194 Oct-20-2019, 06:24 PM
Last Post: Larz60+
  have homework to add a list to a list using append. celtickodiak 2 2,021 Oct-11-2019, 12:35 PM
Last Post: ibreeden
  Search character from 2d list to 2d list AHK2019 3 2,503 Sep-25-2019, 08:14 PM
Last Post: ichabod801
  I donr know how to search from 2d list to 2d list AHK2019 1 1,766 Sep-25-2019, 01:59 AM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020