Back

Code to swap adjacent number

Created 2 years ago
261 Views
1 Comments
SoorajM9zVQ8
@SoorajM9zVQ8
SoorajM9zVQ8
@SoorajM9zVQ8Profile is locked. Login

Question

Given an array of N elements switch(swap) the element with the adjacent element and print the output.
Sample Testcase :
INPUT
5
3 2 1 2 3
OUTPUT
2 3 2 1 3

My Code:

I did this code but can anyone suggest a simplified version to do this! I feel this is too complicated for this problem case.

n = int(input())
l = input()
s =""
count=0
#Swapping alternate Variables like 12345 to 21435
for i in range(0,n-1,2):
    s=s+l[i+1]
    s=s+l[i]
    count=count+1
if (count%2)!=0:
    print(s)
else:
    s = s + l[n - 1]
    print(s)
Comments
Please login to comment.