Saved Bookmarks
| 1. |
Pls answer, Input list of numbers and swap elements at the even location with the elements at the odd location in python? |
|
Answer» Answer: length := size of nums for i in range 0 to length, increase by 4, do if i+2 exchange nums[i] and nums[i+2] if i+3 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 nums[i], nums[i+2] = nums[i+2], nums[i] if(i+3 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] |
|