Advertisement
Guest User

Untitled

a guest
Jan 17th, 2019
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.32 KB | None | 0 0
  1. '''
  2. CSC263 Winter 2019
  3. Problem Set 1 Starter Code
  4. University of Toronto Mississauga
  5. '''
  6.  
  7. # Do NOT add any "import" statements
  8. #Parent(i) = floor(i/2)
  9. #Right(i) = 2i + 1
  10. #Left(i) = 2i
  11.  
  12. def assign_variable(lst,val):
  13. if val > len(lst)-1 or val < 0:
  14. return 0
  15. return val
  16.  
  17. def smallest_child(lst,index):
  18. left_child = assign_variable(lst,index*2)
  19. right_child = assign_variable(lst,index*2 + 1)
  20. return_child = left_child
  21.  
  22. #incase the right child is smaller
  23. if lst[right_child] < lst[left_child]:
  24. return_child = right_child
  25.  
  26. return return_child
  27.  
  28. def bubble_up(lst,index):
  29. root = assign_variable(lst,index//2)
  30. if lst[root] > lst[index]: #Checks if the parent is greater than the child
  31. #Since it is a min heap we must keep the smaller number at the root
  32. lst[root], lst[index] = lst[index], lst[root] #performs the swap
  33. bubble_up(lst,root)
  34. return
  35.  
  36.  
  37. def bubble_down(lst,index):
  38.  
  39. lowest_child = smallest_child(lst,index)
  40.  
  41. #check if the child is smaller than the root, if so we swap
  42. if lst[lowest_child] < lst[index]:
  43. lst[index], lst[lowest_child] = lst[lowest_child], lst[index]
  44. #recursive call incase there needs to be more bubbling down
  45. bubble_down(lst, lowest_child)
  46. return
  47.  
  48.  
  49. def insert(lst,val):
  50. lst.append(val)
  51. bubble_up(lst, len(lst)-1)
  52. return
  53.  
  54. def get_min(lst,counter):
  55. level = 1 # start at first level
  56. target = 0 #keep track of the index
  57. while level != counter:
  58. target = smallest_child(lst,target)
  59. level += 1
  60.  
  61. return lst[target]
  62.  
  63.  
  64.  
  65.  
  66.  
  67. def solve_moving_min(commands):
  68. '''
  69. Pre: commands is a list of commands
  70. Post: return list of get_min results
  71. '''
  72. lst = []
  73. results = []
  74. counter = 0
  75. for words in commands:
  76. if words == 'get_min':
  77. counter += 1
  78. results.append(get_min(lst, counter))
  79. else:
  80. parsed_word = words.split()
  81. insert(lst,parsed_word[1])
  82. return
  83.  
  84.  
  85. if __name__ == '__main__':
  86.  
  87. # some small test cases
  88. # Case 1
  89. assert [10, 5, 10] == solve_moving_min(
  90. ['insert 10',
  91. 'get_min',
  92. 'insert 5',
  93. 'insert 2',
  94. 'insert 50',
  95. 'get_min',
  96. 'get_min',
  97. 'insert -5'
  98. ])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement