Advertisement
Byleth_CYY

Nuts and Bolts 2

May 3rd, 2020
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.78 KB | None | 0 0
  1. """
  2. class Comparator:
  3. def cmp(self, a, b)
  4. You can use Compare.cmp(a, b) to compare nuts "a" and bolts "b",
  5. if "a" is bigger than "b", it will return 1, else if they are equal,
  6. it will return 0, else if "a" is smaller than "b", it will return -1.
  7. When "a" is not a nut or "b" is not a bolt, it will return 2, which is not valid.
  8. """
  9.  
  10. from random import randint
  11. class Solution:
  12. # @param nuts: a list of integers
  13. # @param bolts: a list of integers
  14. # @param compare: a instance of Comparator
  15. # @return: nothing
  16. def sortNutsAndBolts(self, nuts, bolts, compare):
  17. # write your code here
  18. self.sort(nuts, bolts, 0, len(nuts)- 1, compare)
  19.  
  20.  
  21. def sort(self,nuts,bolts,l,r,compare):
  22. if l>=r:
  23. return
  24.  
  25. i,j=l,r
  26. cur_nut=None
  27. pivot=bolts[l]
  28. while i<=j:
  29. while i<=j and compare.cmp(nuts[i],pivot)==-1:
  30. i+=1
  31. while i<=j and compare.cmp(nuts[j],pivot)==1:
  32. j-=1
  33. if i<=j:
  34. nuts[i],nuts[j]=nuts[j],nuts[i]
  35. i+=1
  36. j-=1
  37.  
  38. if compare.cmp(nuts[i],pivot)==0:
  39. cur_nut=nuts[i]
  40. elif compare.cmp(nuts[i-1],pivot)==0:
  41. cur_nut=nuts[i-1]
  42.  
  43. #print(pivot,nuts,i,j)
  44.  
  45. print(pivot,cur_nut,nuts,i,j)
  46. i,j=l,r
  47. while i<=j:
  48. while i<=j and compare.cmp(cur_nut,bolts[i])==1:
  49. i+=1
  50. while i<=j and compare.cmp(cur_nut,bolts[i])==-1:
  51. j-=1
  52. if i<=j:
  53. bolts[i],bolts[j]=bolts[j],bolts[i]
  54. i+=1
  55. j-=1
  56.  
  57. self.sort(nuts,bolts,l,j,compare)
  58. self.sort(nuts,bolts,i,r,compare)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement