Skip to content

WIP: Update deque #440

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 26 additions & 4 deletions python-stdlib/collections.deque/collections/deque.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,47 @@
class deque:
def __init__(self, iterable=None):
def __init__(self, iterable=None, maxlen=None):
if iterable is None:
self.q = []
else:
self.q = list(iterable)
if maxlen is not None:
if not isinstance(maxlen, int):
raise TypeError("" "an integer is required")
if maxlen < 0:
raise ValueError("" "maxlen must be non-negative")
self.__maxlen = maxlen

def popleft(self):
return self.q.pop(0)

def popright(self):
return self.q.pop()

def pop(self):
return self.q.pop()

def remove(self, a):
return self.q.remove(a)

def append(self, a):
self.q.append(a)
if self.__maxlen is not None and len(self.q) > self.__maxlen:
self.popleft()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you could do this bit before appending, to use less memory for the list


def appendleft(self, a):
self.q.insert(0, a)
if self.__maxlen is not None and len(self.q) > self.__maxlen:
self.pop()

def extend(self, a):
if len(self.q) + len(a) > self.__maxlen:
raise IndexError
self.q.extend(a)

def clear(self):
self.q.clear()

@property
def maxlen(self):
return self.__maxlen

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

Expand All @@ -34,3 +53,6 @@ def __iter__(self):

def __str__(self):
return "deque({})".format(self.q)

def __getitem__(self, idx):
return self.q[idx]