Advertisement
hoangreal

inserts the pins to columns with least consumed heights

Oct 21st, 2024
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.67 KB | None | 0 0
  1. """
  2. Given a set of pins with attributes (pin id, height), write a function that takes the argument 'k' (determining the number of columns)
  3. and inserts the pins such that every pin goes into a column with least consumed height. If there is a tie then insert into the left most column.
  4. """
  5.  
  6. def model_pins(pins, n_columns):
  7.     agg_pins = {}
  8.     grid_layout = []
  9.     for i in range(n_columns):
  10.         grid_layout.append([])
  11.         agg_pins[i] = 0
  12.  
  13.     for i in range(n_columns):  # fill first row for all columns
  14.         agg_pins[i] += pins[i]['height']
  15.         grid_layout[i] = [pins[i]]
  16.  
  17.     for i in range(n_columns, len(pins)):
  18.         lowest_height_val = float('Inf')
  19.         aux_index = -1
  20.         for index in range(len(agg_pins)):  # find the column index with lowest height
  21.             if agg_pins[index] < lowest_height_val:  # this covers the most left index in case of a tie
  22.                 lowest_height_val = agg_pins[index]
  23.                 aux_index = index
  24.  
  25.         agg_pins[aux_index] += pins[i]['height']
  26.         grid_layout[aux_index].append(pins[i])
  27.  
  28.     return grid_layout
  29.  
  30.  
  31.  
  32. def main():
  33.     pins = [
  34.         {"id": 1, "height": 300},
  35.         {"id": 2, "height": 200},
  36.         {"id": 3, "height": 250},
  37.         {"id": 4, "height": 350},
  38.         {"id": 5, "height": 100},
  39.     ]
  40.     n_columns = 2
  41.  
  42.     expected_result = [
  43.         [
  44.             {"id": 1, "height": 300},
  45.             {"id": 4, "height": 350},
  46.         ],
  47.         [
  48.             {"id": 2, "height": 200},
  49.             {"id": 3, "height": 250},
  50.             {"id": 5, "height": 100},
  51.         ]
  52.     ]
  53.  
  54.     result = model_pins(pins, n_columns)
  55.     assert result == expected_result
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement