Advertisement
rhettinger

Fix quadratic behavior of PyPy's deque.remove() method

Feb 8th, 2013
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Diff 0.92 KB | None | 0 0
  1. diff --git a/lib_pypy/_collections.py b/lib_pypy/_collections.py
  2. --- a/lib_pypy/_collections.py
  3. +++ b/lib_pypy/_collections.py
  4. @@ -142,12 +142,18 @@
  5.          return c
  6.  
  7.      def remove(self, value):
  8. -        # Need to be defensive for mutating comparisons
  9. -        for i in range(len(self)):
  10. -            if self[i] == value:
  11. -                del self[i]
  12. -                return
  13. -        raise ValueError("deque.remove(x): x not in deque")
  14. +        # Need to defend against mutating or failing comparisons
  15. +        i = 0
  16. +        try:
  17. +            for i in range(len(self)):
  18. +                if self[0] == value:
  19. +                    self.popleft()
  20. +                    return
  21. +                self.append(self.popleft())
  22. +            i += 1
  23. +            raise ValueError("deque.remove(x): x not in deque")
  24. +        finally:
  25. +            self.rotate(i)
  26.  
  27.      def rotate(self, n=1):
  28.          length = len(self)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement