Home > Software design >  How to remove items from list in other class?
How to remove items from list in other class?

Time:10-29

I have a problem here, I need to do method pop but I can only use functions from SimpleList, any ideas?

I can only modify class RingBuffer so I can't use remove(), pop() etc.

from typing import Optional, List

# (‹sl› is instance of ‹SimpleList›):
#
#  • ‹sl.append(x)› adds to the end of list ‹x›,
#  • ‹sl.get(i)› returns value of index ‹i›,
#  • ‹sl.size()› returns current size of list,
#  • ‹sl.set(i, x)› sets index ‹i› to value ‹x›.

class RingBuffer:

    def __init__(self, size: int, storage: 'SimpleList'):
        self.sl = storage
        self.size = size

    def push(self, value: int) -> bool:
        if self.sl.size() >= self.size:
            return False
        else:
            self.sl.append(value)
            return True

    # Method ‹pop› removes first value from list and returns it.
    # If list is empty, method doesn't do anything and returns ‹None›.

    def pop(self) -> Optional[int]:
        if self.sl.size() == 0:
            return None

class SimpleList:

    def __init__(self) -> None:
        self.__items: List[int] = []
    def append(self, x: int) -> None:
        self.__items.append(x)
    def get(self, i: int) -> int:
        return self.__items[i]
    def set(self, i: int, x: int) -> None:
        self.__items[i] = x
    def size(self) -> int:
        return len(self.__items)

CodePudding user response:

I think you figured it out, but just for you to compare:

def pop(self) -> Optional[int]:
    if self.sl.size() == 0:
        return None
    
    l = [(self.sl.get(x)) for x in range(self.sl.size())]
    self.sl = SimpleList()
    [self.sl.append(x) for x in l[1:]]
    return l[0]
  • Related