Showing posts with label Write a program that take list L as an input and shifts all zeroes in list L towards the right by maintaining the order of the list. Also print the new list.. Show all posts
Showing posts with label Write a program that take list L as an input and shifts all zeroes in list L towards the right by maintaining the order of the list. Also print the new list.. Show all posts
Saturday, March 11, 2023

Write a program that take list L as an input and shifts all zeroes in list L towards the right by maintaining the order of the list. Also print the new list.



Write a program that take list L as an input and shifts all zeroes in list L towards the right by maintaining the order of the list. Also print the new list.


Input:

[0,1,0,3,12]

Output:

[1,3,12,0,0]

Explanation:

There are two zeroes in the list which are shifted to the right and the order of the list is also maintained. (1,3,12 are in order as in the old list.)

Python Code :

def shift_zeros_right(L):
    # Create a new list to store the shifted elements
    shifted_list = []
    
    # Iterate through the original list
    for i in range(len(L)):
        # If the current element is not zero, append it to the shifted list
        if L[i] != 0:
            shifted_list.append(L[i])
    
    # Append the remaining zeros to the end of the shifted list
    num_zeros = len(L) - len(shifted_list)
    shifted_list += [0] * num_zeros
    
    # Return the shifted list
    return shifted_list


L=[int(i) for i in input().split()]
shifted_list = shift_zeros_right(L)
print(shifted_list,end="")