Program to pack same consecutive elements into sublist in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of numbers nums, we will pack consecutive elements of the same value into sublists. We have to keep in mind that there is only one occurrence in the list it should still be in its own sublist.

So, if the input is like nums = [5, 5, 2, 7, 7, 7, 2, 2, 2, 2], then the output will be [[5, 5], [2], [7, 7, 7], [2, 2, 2, 2]]

To solve this, we will follow these steps −

  • if nums is empty, then
    • return a new list
  • result := a list with another list that contains nums[0]
  • j := 0
  • for i in range 1 to size of nums, do
    • if nums[i] is not same as nums[i - 1], then
      • insert a new list at the end of result
      • j := j + 1
    • insert nums[i] at the end of result[j]
  • return result

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, nums):
      if not nums:
         return []
      result = [[nums[0]]]
      j = 0
      for i in range(1, len(nums)):
         if nums[i] != nums[i - 1]:
            result.append([])
            j += 1
            result[j].append(nums[i])
      return result
ob = Solution()
nums = [5, 5, 2, 7, 7, 7, 2, 2, 2, 2]
print(ob.solve(nums))

Input

[5, 5, 2, 7, 7, 7, 2, 2, 2, 2]

Output

[[5, 5], [2], [7, 7, 7], [2, 2, 2, 2]]
raja
Published on 20-Oct-2020 07:07:07
Advertisements