Last active
September 23, 2018 18:19
-
-
Save bact/4549cef22c9c7de2c85e8178eacdd9e4 to your computer and use it in GitHub Desktop.
Find if a list of int can be sorted by only one swap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def is_one_swap_can_sort(nums): | |
sorted_nums = sorted(nums) | |
if nums == sorted_nums: | |
return True | |
len_nums = len(nums) | |
for i in range(len_nums): | |
for j in range(i+1, len_nums): | |
test = nums.copy() | |
if test[i] > test[j]: | |
temp = test[i] | |
test[i] = test[j] | |
test[j] = temp | |
if test == sorted_nums: | |
return True | |
return False | |
questions_answers = [ | |
([1,2,4,5,3], False), | |
([1,3,3,4,5], True), | |
([1,2,3,4,5], True), | |
([1,3,2,5,4], False), | |
([5,2,3,4,1], True), | |
([5,4,4,1,6], True), | |
([2,6,6,5], True), | |
([5,6,6,1], False), | |
([1], True), | |
([], True), | |
] | |
for question, answer in questions_answers: | |
myanswer = is_one_swap_can_sort(question) | |
is_wrong = 'XXX' if myanswer != answer else '' | |
print("{} => {} (Expected: {}) {}".format(question, myanswer, answer, is_wrong)) |
This one by @9terz is more clever, sort then count differences:
https://gist.github.com/9terz/efa8d2b13840a7dfba07f5228af144e1
same logic with @salamtamp (in JavaScript):
https://gist.github.com/salamtamp/ed46781954d659f24dff223090fe5203
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
แก้แล้วๆ เพิ่ม test case เข้าไปอีกสองอัน คือกรณี list ว่าง กับ list มีสมาชิกตัวเดียว