Advertisement
Guest User

Untitled

a guest
Apr 24th, 2019
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.04 KB | None | 0 0
  1. """
  2. Question:
  3. Mary can perform the following minimal sequence of swap operations to
  4. successfully sort all 3 items by decreasing popularity rating: [3, 1, 2] → [3, 2, 1].
  5.  
  6. Solution:
  7. 1. The swap always compares the last element in the array with
  8. the least element in the remaining list e.g.
  9. in the case of [3, 1, 2, 4]...we compare 4 with the minimum value in [3,1,2]
  10. and swap the two if the minimum value is less
  11. 2. Repeat 1 until the the list is sorted in descending order
  12. 3. Do the above while counting the swaps"""
  13.  
  14. def minimum_swaps(ratings):
  15. if sorted(ratings, reverse=True) == ratings:
  16. return 0
  17. swaps = 1
  18. while sorted(ratings, reverse=True) != sorter(ratings):
  19. swaps += 1
  20. return swaps
  21.  
  22. def sorter(array):
  23.  
  24. for i in sorted(range(len(array)), reverse=True):
  25. comp = array[:i]
  26. if len(comp) > 0:
  27. mini = min(comp)
  28.  
  29. if mini < array[i]:
  30. index = array.index(mini)
  31.  
  32. array[i], array[index] = array[index], array[i]
  33. return array
  34.  
  35. return array
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement