Program to sqeeze list elements from left or right to make it single element in Python


Suppose we have a list of numbers called nums, we have to squeeze it from both the left and the right until there is one remaining element. We will return the states at each step.

So, if the input is like nums = [10,20,30,40,50,60], then the output will be

[ [10, 20, 30, 40, 50, 60],
   [30, 30, 40, 110],
   [60, 150],
   [210]
]

To solve this, we will follow these steps −

  • ret := a list with only one element nums
  • while size of nums > 1, do
    • if size of nums is same as 2, then
      • nums := make a list with element (nums[0] + nums[1])
    • otherwise when size of nums is same as 3, then
      • nums := make a list with element (nums[0] + nums[1] + nums[2])
    • otherwise,
      • nums := make a list with elements (nums[0] + nums[1]) then insert another list from nums from index 2 to third last element of nums then add another list with element (second last element of nums + last element of nums)
    • insert nums at the end of ret
  • return ret

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, nums):
      ret = [nums]
      while len(nums) > 1:
         if len(nums) == 2:
            nums = [nums[0] + nums[1]]
         elif len(nums) == 3:
            nums = [nums[0] + nums[1] + nums[2]]
         else:
            nums = [nums[0] + nums[1]] + nums[2:-2] + [nums[-2] + nums[-1]]
            ret.append(nums)
      return ret
ob = Solution() print(ob.solve([10,20,30,40,50,60]))

Input

[10,20,30,40,50,60]

Output

[[10, 20, 30, 40, 50, 60], [30, 30, 40, 110], [60, 150], [210]]

Updated on: 05-Oct-2020

116 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements