高级农民
- 积分
- 1236
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2018-12-20
- 最后登录
- 1970-1-1
|
- def rebalance(slots):
- # calculate the average number of slots per server
- avg_slots = sum(slots.values()) / len(slots)
- # store the slots that need to be moved
- moves = []
- # for each server
- for server, num_slots in slots.items():
- # if the server has more slots than the average
- if num_slots > avg_slots:
- # calculate the number of extra slots
- extra_slots = num_slots - avg_slots
- # divide the extra slots evenly among the other servers
- for target_server, target_slots in slots.items():
- # skip the current server
- if target_server == server:
- continue
- # calculate the number of slots to move
- move_slots = min(extra_slots, avg_slots - target_slots)
- # add the move to the list of moves
- moves.append((server, target_server, move_slots))
- # update the number of slots for the current server and target server
- slots[server] -= move_slots
- slots[target_server] += move_slots
- # decrease the extra slots by the number of slots moved
- extra_slots -= move_slots
- return moves
- # example input
- slots = {
- "A": 5000,
- "B": 5000,
- "C": 6384
- }
- print(rebalance(slots))
- # Output: [(C, A, 461), (C, B, 461)]
- # After the rebalance: A has 5461 slots, B has 5461 slots, C has 5462 slots
复制代码 |
|