Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- This problem was asked by Amazon.
- Run-length encoding is a fast and simple method of encoding strings. The basic idea is to represent repeated successive characters as a single count
- and character. For example, the string "AAAABBBCCDAA" would be encoded as "4A3B2C1D2A".
- Implement run-length encoding and decoding. You can assume the string to be encoded have no digits and consists solely of alphabetic characters.
- You can assume the string to be decoded is valid.
- '''
- from timeit import default_timer as timer
- def solve(message):
- n = len(message)
- letters = list()
- letters.append(message[0])
- counters = list()
- counters.append(1)
- for i in range(1, n):
- if message[i] == letters[len(letters)-1]:
- counters[len(counters)-1] += 1
- else:
- letters.append(message[i])
- counters.append(1)
- # Now, I have to create the returned string based on the 2 lists
- result = ""
- if len(letters) != len(counters):
- print("Error using function 'solve'.")
- return -1000
- for i in range(len(letters)):
- result += (str(counters[i]) + letters[i])
- return result
- def prettyPrint(message):
- start = timer()
- result = solve(message)
- end = timer()
- elapsed = 10**6 * (end - start)
- print(message + " ----> " + str(result) + " (" + str(round(elapsed, 2)) + " μs)")
- # MAIN FUNCTION
- print()
- messages = ["AAAAAAAAAKK", "AAAABBBCCDAA", "AAABBBaaabbbAAA", "asdfQWE"]
- for message in messages:
- prettyPrint(message)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement