Asked in sap labs/Amazon


Given a string, Your task is to complete the function encode that returns the run length encoded string for the given string.
eg if the input string is “wwwwaaadexxxxxx”, then the function should return “w4a3d1e1x6″.
You are required to complete the function encode that takes only one argument the string which is to be encoded and returns the encoded string.


The solution in Python is
s=“wwwwaaadexxxxxx”#Given Input
list1=[]#Empty List
list2=[]#Empty List
list1=list(s)#list of characters in string
for i in s:
if i not in list2:
list2.append(i)#building another list with unique characters of string
print(list1)#output for this statement[‘w’, ‘w’, ‘w’, ‘w’, ‘a’, ‘a’, ‘a’, ‘d’, ‘e’, ‘x’, ‘x’, ‘x’, ‘x’, ‘x’, ‘x’]
print(list2)#output for this statement[‘w’, ‘a’, ‘d’, ‘e’, ‘x’]
res=""#enoded string
for i in list2:
res+=i+str(list1.count(i))#iterate over list1 and count the occurences using list2 and built the encoded string