Advertisement
chrisreall

Untitled

Jan 12th, 2020
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.18 KB | None | 0 0
  1. ### Update 0:07 1/14/2020 Didn't test the tests. I was checking the opposite of what I wanted, which resulted in switching the functionality of __gt__ with __lt__ (kind of). It's since been fixed (although the SO question was also answered, so this code can probably, safely be ignored)
  2.  
  3. from typing import Iterator
  4. from unittest import TestCase
  5.  
  6.  
  7. class ILengthComparator:
  8.     def __init__(self, iterator: Iterator):
  9.         self.iterator = iterator
  10.  
  11.     def has_more(self) -> bool:
  12.         try:
  13.             next(self.iterator)
  14.         except StopIteration:
  15.             return False
  16.  
  17.         return True
  18.  
  19.     def __eq__(self, length: int) -> bool:
  20.         if length < 0:
  21.             return False
  22.  
  23.         if not self.has_more():
  24.             return length == 0
  25.  
  26.         return self == length - 1
  27.  
  28.     def __gt__(self, length: int) -> bool:
  29.         if length < 0:
  30.             return True
  31.  
  32.         if not self.has_more():
  33.             return False
  34.  
  35.         return self > length - 1
  36.  
  37.     def __lt__(self, length: int) -> bool:
  38.         if length < 1:
  39.             return False
  40.  
  41.         if not self.has_more():
  42.             return True
  43.  
  44.         return self < length - 1
  45.  
  46.  
  47. class TestCmpIterLength(TestCase):
  48.     def test__eq(self):
  49.         test_inputs = [(iter(range(10)), i) for i in range(-5, 15)]
  50.         expected_outputs = [10 == i for i in range(-5, 15)]
  51.         actual_outputs = [ILengthComparator(test_iter) == test_length for test_iter, test_length in test_inputs]
  52.         self.assertEqual(expected_outputs, actual_outputs)
  53.  
  54.     def test__lt(self):
  55.         test_inputs = [(iter(range(10)), i) for i in range(-5, 15)]
  56.         expected_outputs = [10 < i for i in range(-5, 15)]
  57.         actual_outputs = [ILengthComparator(test_iter) < test_length for test_iter, test_length in test_inputs]
  58.         self.assertEqual(expected_outputs, actual_outputs)
  59.  
  60.     def test__gt(self):
  61.         test_inputs = [(iter(range(10)), i) for i in range(-5, 15)]
  62.         expected_outputs = [10 > i for i in range(-5, 15)]
  63.         actual_outputs = [ILengthComparator(test_iter) > test_length for test_iter, test_length in test_inputs]
  64.         self.assertEqual(expected_outputs, actual_outputs)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement