Subscribe to Tech With Tim!
Download All: Download Now
This is an intermediate level programming problem. It shouldn’t take you more than 20 minutes to complete. For your reference it took me (Tech With Tim) 5 minutes to complete.
Watch the video for a full explanation of the solution.
# GET INPUT FROM LINE ''' n = int(input()) lines =  for _ in range(n): lines.append(input())''' # GET INPUT FROM TEXT FILE with open("input.txt", "r") as f: lines = f.readlines() # SOLVE PROBLEM for line in lines[1:]: # For each input line = line.strip() # Remove \n from line newStr = "" last = line count = 1 for char in line[1:]: # For every character except the first (because we already handled it above) if char == last: # If the next character is equal to the last (consecutive chars) count += 1 else: # If the next character is different newStr += str(count) + " " + last + " " count = 1 last = char newStr += str(count) + " " + last print(newStr)