233k views
3 votes
Assume that someone dictates you a sequence of numbers and you need to write it down. For brevity, he dictates it as follows: first says the number of consecutive identical numbers and then says the number itself. E.g. The sequence 1 1 3 3 3 2 2 2 2 14 14 14 11 11 11 2 will be dictated as "Two one, three three, four twos, three fourteens, three elevens, one two", so you will write down the sequence 2 1 3 3 4 2 3 14 3 11 1 2. The challenge is to write the program which compresses the given sequence using this approach. Input: Your program should read lines from standard input. Each line is a sequence of L integers, where each integer is N, separated by a whitespace. N is in range [0, 99]. L is in range [1, 400]. Output: For each test case, produce a single line of output containing a compressed sequence of numbers separated by a single space char.

User Ariel
by
6.3k points

1 Answer

0 votes

Answer:

We have the following code in python with appropriate comments

Step-by-step explanation:

line = input("Enter your line of integers: ")

# Splits at space

intList = line.split()

#initializing the count to 1

count = 1

#initializing the count to empty string

output = ''

#iterating over the list

for index, x in enumerate(intList):

#handling last index separately

if index == len(intList)-1:

if intList[index] == intList[index-1]:

output = output + str(count) + ' ' + str(intList[index])

else:

count = 1

output = output + str(count) + ' ' + str(intList[index])

#handling indexes other than the last index

else:

if intList[index]==intList[index+1]:

count = count + 1 #if next integer is same, we increase the count by 1

else:

output = output + str(count) + ' ' + str(intList[index]) + ' '

count = 1

print(output)

User Tom Harrington
by
5.6k points