Benjamin Peterson | d7b0eeb | 2009-07-19 20:18:21 +0000 | [diff] [blame] | 1 | """Various utility functions.""" |
| 2 | |
Michael Foord | 225a099 | 2010-02-18 20:30:09 +0000 | [diff] [blame^] | 3 | def safe_repr(obj): |
| 4 | try: |
| 5 | return repr(obj) |
| 6 | except Exception: |
| 7 | return object.__repr__(obj) |
| 8 | |
Benjamin Peterson | d7b0eeb | 2009-07-19 20:18:21 +0000 | [diff] [blame] | 9 | def strclass(cls): |
| 10 | return "%s.%s" % (cls.__module__, cls.__name__) |
| 11 | |
| 12 | def sorted_list_difference(expected, actual): |
| 13 | """Finds elements in only one or the other of two, sorted input lists. |
| 14 | |
| 15 | Returns a two-element tuple of lists. The first list contains those |
| 16 | elements in the "expected" list but not in the "actual" list, and the |
| 17 | second contains those elements in the "actual" list but not in the |
| 18 | "expected" list. Duplicate elements in either input list are ignored. |
| 19 | """ |
| 20 | i = j = 0 |
| 21 | missing = [] |
| 22 | unexpected = [] |
| 23 | while True: |
| 24 | try: |
| 25 | e = expected[i] |
| 26 | a = actual[j] |
| 27 | if e < a: |
| 28 | missing.append(e) |
| 29 | i += 1 |
| 30 | while expected[i] == e: |
| 31 | i += 1 |
| 32 | elif e > a: |
| 33 | unexpected.append(a) |
| 34 | j += 1 |
| 35 | while actual[j] == a: |
| 36 | j += 1 |
| 37 | else: |
| 38 | i += 1 |
| 39 | try: |
| 40 | while expected[i] == e: |
| 41 | i += 1 |
| 42 | finally: |
| 43 | j += 1 |
| 44 | while actual[j] == a: |
| 45 | j += 1 |
| 46 | except IndexError: |
| 47 | missing.extend(expected[i:]) |
| 48 | unexpected.extend(actual[j:]) |
| 49 | break |
| 50 | return missing, unexpected |