Before writing a script in python to do the task, let's see how we'd do this manually. Let's follow the given algorithm and see how it works.
Procedure:
Step 0: Take an empty string, named output_string
.
Step 1: Take an empty sequence_list
.
Step 2: Take the element (number) at the start of number_list
, see if it can be added to sequence_list
, then add the number to the sequence_list
and remove it from number_list
, and repeat Step 2. Otherwise, go to Step 3.
Step 3: Compress sequence_list
to a string, and add it to output.
Step 4: If number_list
is not empty, go to Step 1 again. Otherwise, display the output_string
.
Let's take one iteration over the list in question for example.
number_list = [1,2,3,4,5,9,10,11,12,18,19,40]
After Step 0:
output_string = ""
After Step 1:
sequence_list = []
After Step 2: (Iterating 5 times)
sequence_list = [1, 2, 3, 4, 5]
number_list = [9,10,11,12,18,19,40]
Since, our next element is 9, which we can't add to the sequence list, we move to Step 3
After Step 3
output_string = "1-5"
number_list = [9,10,11,12,18,19,40]
At Step 4
Since, our number_list
is not empty, we return to Step 1, and the whole process repeats for 3 more times. After which we get following output_string
output_string = "1-5,9-12,18-19,40"
This is the output we require. So, we are done.
Python Script for the same:
def numlist_string(numlist):
# If the length of list is 1 then we don't need to write it in the
# form x-y, because that increases the number characters in string
if(len(numlist) == 1):
return "{}".format(numlist[0])
else:
numlist_last = len(numlist) - 1
return "{}-{}".format(numlist[0], numlist[numlist_last])
def numlist_compress(numlist):
if(len(numlist) == 0):
return []
compressed_list = []
for i in range(len(numlist)):
if(numlist[i] != numlist[0] + i):
# Sequence is broken
# Splitting up list into sequence and remaining
req_list = numlist[0 : i]
rem_list = numlist[i : ]
# Getting sequence list as a string
numlist_s = numlist_string(req_list)
# Adding sequence string to the list of strings
compressed_list.append(numlist_s)
# Compressing the remaining list and adding that to previously
# generated sequence string
compressed_list.extend(numlist_compress(rem_list))
return compressed_list
# Whole list is a sequence
numlist_s = numlist_string(numlist)
compressed_list.append(numlist_s)
return compressed_list
if __name__ == '__main__':
number_list = [1,2,3,4,5,9,10,11,12,18,19,40]
sequence_list = numlist_compress(number_list)
sequence_string = ','.join(sequence_list)
print(sequence_string)