Pls answer, Input list of numbers and swap elements at the even location with the elements at the odd location in python?
Answers
Answered by
5
Answer:
length := size of nums
for i in range 0 to length, increase by 4, do
if i+2<length, then
exchange nums[i] and nums[i+2]
if i+3<length, then
exchange nums[i+1] and nums[i+3]
return nums
Let us see the following implementation to get better understanding −
Example
Live Demo
class Solution:
def solve(self, nums):
length = len(nums)
for i in range(0,length,4):
if(i+2<length):
nums[i], nums[i+2] = nums[i+2], nums[i]
if(i+3<length):
nums[i+1], nums[i+3] = nums[i+3], nums[i+1]
return nums
ob = Solution()
nums = [1,2,3,4,5,6,7,8,9]
print(ob.solve(nums))
Input
[1,2,3,4,5,6,7,8,9]
Output
[3, 4, 1, 2, 7, 8, 5, 6, 9]
Similar questions
Geography,
1 month ago
Social Sciences,
1 month ago
Physics,
3 months ago
Math,
9 months ago
Math,
9 months ago