Paired sotring
          Created
          November 1, 2021 19:08 
        
      - 
      
- 
        Save davidlatwe/a729e06c54b712db72516d17fdbcbe98 to your computer and use it in GitHub Desktop. 
    Paired sotring
  
        
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | from random import randint | |
| class Foo: | |
| def __init__(self, attr, x): | |
| self.attr = attr | |
| self.x = x | |
| def __eq__(self, other): | |
| if isinstance(other, Foo): | |
| return self.attr == other.attr | |
| def __repr__(self): | |
| return "F(a=%02d)" % self.attr | |
| class NoVel: | |
| def __repr__(self): | |
| return "_( )" | |
| none = NoVel() | |
| def generator(count): | |
| for attr in range(count): | |
| r = randint(0, 3) | |
| if r == 0: | |
| yield Foo(attr, True) | |
| yield None | |
| if r == 1: | |
| yield None | |
| yield Foo(attr, False) | |
| if r >= 2: | |
| yield Foo(attr, True) | |
| yield Foo(attr, False) | |
| revs = [f for f in generator(20) if f is not None] | |
| sorted_revs = sorted( | |
| revs, key=lambda r: (r.attr, -r.x) | |
| ) | |
| paired_revs = {"L": [], "R": []} | |
| for i, rev in enumerate(sorted_revs): | |
| if rev.x: | |
| paired_revs["R"].append(rev) | |
| paired_revs["L"].append(none) | |
| else: | |
| if paired_revs["R"] and paired_revs["R"][-1] == rev: | |
| paired_revs["L"][-1] = rev | |
| else: | |
| paired_revs["R"].append(none) | |
| paired_revs["L"].append(rev) | |
| print(paired_revs["R"]) | |
| print(paired_revs["L"]) | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment