- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Swap Consecutive Even Elements in Python
Suppose we have a list of numbers called nums, we have to exchange every consecutive even integer with each other.
So, if the input is like nums = [4, 5, 6, 8, 10], then the output will be [6, 5, 4, 10, 8]
To solve this, we will follow these steps −
- temp := null
- for i in range 0 to size of nums, do
- if nums[i] mod 2 is same as 0, then
- if temp is not null, then
- exchange nums[i], nums[temp]
- temp := null
- otherwise,
- temp := i
- if temp is not null, then
- if nums[i] mod 2 is same as 0, then
- return nums
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, nums): temp = None for i in range(len(nums)): if nums[i] % 2 == 0: if temp is not None: nums[i], nums[temp] = nums[temp], nums[i] temp = None else: temp = i return nums ob = Solution() print(ob.solve([4, 5, 6, 8, 10]))
Input
[4, 5, 6, 8, 10]
Output
[6, 5, 4, 10, 8]
Advertisements