diff --git a/Short-Answer/Algorithms_Answers.md b/Short-Answer/Algorithms_Answers.md index b276aca1b..ce1c9efd9 100644 --- a/Short-Answer/Algorithms_Answers.md +++ b/Short-Answer/Algorithms_Answers.md @@ -2,14 +2,20 @@ ## Exercise I -a) +a) O(n) because of the while loop -b) +b) O(n^2) because of the two loops -c) +c) O(n) because this one calls itself recursively ## Exercise II +I would use a binary search to minimize the number of broken eggs. +start = 0 +end = len(f) +mid = (start + end) // 2 + +By starting at the middle of all the floors, we can see whether or not the egg breaks at the mid level of the building. If it breaks, eliminate all the floors above the middle floor and repeat until it does break. If it doesn't break, eliminate all the floors below that floor and repeat. Runtime for the binary search is O(log n) because every time we run it we're cutting in half the number of options \ No newline at end of file diff --git a/recursive_count_th/count_th.py b/recursive_count_th/count_th.py index 07456a00b..d29b219a8 100644 --- a/recursive_count_th/count_th.py +++ b/recursive_count_th/count_th.py @@ -4,7 +4,14 @@ Your function must utilize recursion. It cannot contain any loops. ''' def count_th(word): - - # TBC - - pass + char1 = 't' + char2 = 'h' + + if len(word) <= 1: + return 0 + + if word[0] == char1: + if word[1] == char2: + return 1 + count_th(word[2:]) + + return count_th(word[1:]) diff --git a/robot_sort/robot_sort.py b/robot_sort/robot_sort.py index db6b1985b..a676c8ee9 100644 --- a/robot_sort/robot_sort.py +++ b/robot_sort/robot_sort.py @@ -97,7 +97,35 @@ def sort(self): Sort the robot's list. """ # Fill this out - pass + + # get item + self.swap_item() + + # while able to move right, move right and turn on the light + while self.can_move_right(): + self.move_right() + # check if light is on + if self.light_is_on == False: + self.set_light_on + + # if the item is less than what the robot is holding, swap item + if self.compare_item() == 1: + self.swap_item() + + # once at the end of the list, go back to the starting point + # on the left side that is empty + while self.can_move_left() and self.compare_item() is not None: + self.move_left() + + # drop item + self.swap_item() + + if self.can_move_right(): + self.move_right() + self.sort() + + else: + self.set_light_off() if __name__ == "__main__":