|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# @author slandau3 |
| 3 | + |
| 4 | + |
| 5 | +def reorder(input: list) -> list: |
| 6 | + neg_index, pos_index = find_neg_and_pos_index(input) |
| 7 | + |
| 8 | + # Square the list. Can also be done with a list comprehension (probably) |
| 9 | + for i in range(len(input)): |
| 10 | + input[i] **= 2 |
| 11 | + |
| 12 | + re_ordered = [] |
| 13 | + |
| 14 | + # This is the part where we go through the square list and essentially re order it. |
| 15 | + # We kept track of the index where the least negative integer was so we can re order this in O(N) time |
| 16 | + # Think about it this way [-3, 0, 2]. neg_index would be 0 and pos_index would be 1. |
| 17 | + # The squared list would be [9, 0, 4] |
| 18 | + # We would now compare 9 and 0, we see that 0 is smaller so that gets appended to re_ordered first. |
| 19 | + # We then increment pos_index so it is now 2 (which equals 4 in this case) |
| 20 | + # we now compare 4 and 9 and see that 4 is smaller so that gets appended to re_ordered |
| 21 | + # Go around again and append 9 |
| 22 | + while len(re_ordered) != len(input): |
| 23 | + if input[neg_index] < input[pos_index]: |
| 24 | + # if the input at negative index is smaller, append input[neg_index] to the new list |
| 25 | + re_ordered.append(input[neg_index]) |
| 26 | + neg_index -= 1 |
| 27 | + elif input[neg_index] >= input[pos_index]: |
| 28 | + # if the input at both indexes is the same or pos_index's value is smaller |
| 29 | + # append input[pos_index] to re_ordered |
| 30 | + re_ordered.append(input[pos_index]) |
| 31 | + if pos_index != len(input)-1: |
| 32 | + # We don't want to get an index out of bounds error so don't do anything if we hit |
| 33 | + # the last value |
| 34 | + pos_index += 1 |
| 35 | + |
| 36 | + return re_ordered |
| 37 | + |
| 38 | + |
| 39 | +def find_neg_and_pos_index(sorted_list: list): |
| 40 | + """ |
| 41 | + Finds the least negative, negative value and the least positive, positive value (including 0). |
| 42 | + :param sorted_list: The (un-squared) input list |
| 43 | + :return: The negative index and positive index |
| 44 | + """ |
| 45 | + neg_index = 0 |
| 46 | + pos_index = 0 |
| 47 | + pos_evaluated = False |
| 48 | + for i in range(len(sorted_list)): |
| 49 | + if sorted_list[i] < 0: # find the least negative, negative number |
| 50 | + neg_index = i |
| 51 | + if sorted_list[i] >= 0 and not pos_evaluated: # Find the least positive positive number |
| 52 | + # This includes 0 |
| 53 | + pos_index = i |
| 54 | + pos_evaluated = True |
| 55 | + |
| 56 | + if sorted_list[neg_index] == 0: |
| 57 | + neg_index = len(sorted_list) |
| 58 | + |
| 59 | + return neg_index, pos_index |
| 60 | + |
| 61 | +if __name__ == '__main__': |
| 62 | + print(reorder([-100,-50,-2,-1,80,900,9001])) |
| 63 | + |
0 commit comments