Advertisement
alex0sunny

rle

Sep 5th, 2022 (edited)
931
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.56 KB | None | 0 0
  1. def rle(word):
  2.     out = []
  3.     back = 0
  4.     for front, char in enumerate(word):
  5.         if not char.isalpha() or not char.isupper():
  6.             raise Exception('char is not upper case letter:' + char)
  7.         if front == len(word) - 1 or char != word[front+1]:
  8.             out.append(word[back])
  9.             count = front + 1 - back
  10.             if count > 1:
  11.                 out.append(str(count))
  12.             back = front+1
  13.     return ''.join(out)
  14.  
  15.  
  16. assert rle('AABB') == 'A2B2'
  17. assert rle('AAAABBBCCXYZ') == 'A4B3C2XYZ'
  18. assert rle('') == ''
  19. # rle('AaA')
  20.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement