Search code examples
pythonlistswap

elements which are multiples of 10 are swapped


The elements which are multiples of 10 are swapped with the value present in the very next position in the list.

For example If the content of list P is:

[91, 50, 54, 22, 30, 54]

Then content of list P should become:

[91, 54, 50, 22, 54, 30]

But I am getting something like:

[91, 54, 50, 54, 22, 54, 30, 54]

The non multiple of 10 element is getting reapeted.

Can someone give me a solution to it. Thanks.

NOTE: It is assumed that consecutive elements are not multiple of 10. And the last element is not a multiple of 10.

   l=[]
   c=[]
   n=int(input("Enter number of elements:"))
   for i in range(1,n+1):
    b=int(input("Enter element:"))
    l.append(b)
   s=len(l)
   for i in range(s): 
   if l[i] % 10 == 0: 
    c.append(l[i+1])
    c.append(l[i])
    i+=1
   else:
    c.append(l[i])
   print(c)

Solution

  • In this case you can't go forward because you would move the target elements all the way to the end. A nice trick to avoid this is to loop backwards, then it's very easy.

    Disclaimer: This doesn't work for consecutive multiples of ten as pointed out by Daniel Hao below!!

    data = [91, 50, 54, 22, 30, 54]
    
    for i in reversed(range(len(data))):
        if data[i] % 10 == 0:
            # move the item one slot to the right
            data.insert(i+1, data.pop(i))