Advertisement
Guest User

Untitled

a guest
Aug 23rd, 2019
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.05 KB | None | 0 0
  1. """
  2. Write function which takes string AAAAaaBCCCDDe as argument and returns its
  3. compressed version A4a2B1C3D2e1
  4. """
  5.  
  6.  
  7. def string_compressor(string):
  8. compresssed = ""
  9. count = 1
  10.  
  11. # Add in the very first character
  12. compresssed += string[0]
  13.  
  14. # Iterate, skipping the last one
  15. for i in range(len(string) - 1):
  16. if string[i] == string[i + 1]:
  17. count += 1
  18. else:
  19. compresssed += str(count)
  20. compresssed += string[i + 1]
  21. count = 1
  22.  
  23. compresssed += str(count)
  24.  
  25. return compresssed
  26.  
  27.  
  28. def test_string_compressor():
  29. test_cases = [
  30. ("AAAAaaBCCCDDe", "A4a2B1C3D2e1"),
  31. ("AAAaBCCCDDe", "A3a1B1C3D2e1"),
  32. ]
  33.  
  34. for (arg, answer) in test_cases:
  35. result = string_compressor(arg)
  36. print("Running Test with data:", arg, "gave = ", result)
  37. if result != answer:
  38. print("\x1b[0;30;41m" + "Test with data:", arg, "failed" + "\x1b[0m")
  39. else:
  40. print("\x1b[6;30;42m" + "Test with data:", arg, "passed" + "\x1b[0m")
  41.  
  42.  
  43. test_string_compressor()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement