
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check If Array Can Be Sorted with One Swap in Python
Suppose, we are provided with an array that contains integer elements. We have to find out if the values in the array can be sorted in a non-decreasing order if we can perform only one swap operation. If possible, we say it can be done, otherwise not.
So, if the input is like input_list = [7, 8, 12, 10, 11, 9], then the output will be “Can be done”
To solve this, we will follow these steps −
- temp_list := a copy of the list input_list
- sort the list temp_list
- swap_count := 0
- for i in range 0 to size of input_list, do
- if input_list[i] is not same as temp_list[i], then
- swap_count := swap_count + 1
- if input_list[i] is not same as temp_list[i], then
- if swap_count is same as 0 or swap_count is same as 2, then
- return True
- otherwise,
- return False
Let us see the following implementation to get better understanding −
Example
from copy import deepcopy def solve(input_list): temp_list = deepcopy(input_list) temp_list.sort() swap_count = 0 for i in range(len(input_list)): if input_list[i] != temp_list[i]: swap_count += 1 if swap_count == 0 or swap_count == 2: print("Can be done") else: print("Can't be done") input_list = [7, 8, 12, 10, 11, 9] solve(input_list)
Input
[7, 8, 12, 10, 11, 9]
Output
Can be done
Advertisements