Skip to content

Instantly share code, notes, and snippets.

@bact
Last active September 23, 2018 18:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bact/4549cef22c9c7de2c85e8178eacdd9e4 to your computer and use it in GitHub Desktop.
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
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))
@bact
Copy link
Author

bact commented Sep 23, 2018

แก้แล้วๆ เพิ่ม test case เข้าไปอีกสองอัน คือกรณี list ว่าง กับ list มีสมาชิกตัวเดียว

@bact
Copy link
Author

bact commented Sep 23, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment