Last active
February 20, 2022 14:24
-
-
Save KMurphs/68a5566c7078df10fe479a32820f2be6 to your computer and use it in GitHub Desktop.
For the Priority Queue Medium Article
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def add_fans(machine_consumptions, total_initial_consumption, n_fans): | |
# Find the machine that has the largest amount of consumption and the | |
# current total amount of consumption for the company | |
max_index, max_value, current_total_consumption = 0, machine_consumptions[0], 0 | |
for machine_index in range(len(machine_consumptions)): | |
# Compute factory consumption | |
current_total_consumption = current_total_consumption + machine_consumptions[machine_index] | |
# Find worse machine with largest consumption so far | |
if max_value < machine_consumptions[machine_index]: | |
max_index, max_value = machine_index, machine_consumptions[machine_index] | |
# Resolve the recursion, because we have reached the target: "just below half of initial consumption" | |
if current_total_consumption <= total_initial_consumption / 2: | |
return n_fans | |
# Update the consumption of the worse machine given the effect of the fan we just placed | |
machine_consumptions[max_index] = max_value / 2 | |
# Recurse, and place a fan on the new worse machine | |
return add_fans(machine_consumptions, total_initial_consumption, n_fans + 1) | |
def solution(A): | |
# write your code in Python 3.6 | |
# This is a greedy algorithm, that will try to put fans first on those machines | |
# that have the largest contribution to the overall factory consumption | |
return add_fans(A, sum(A), 0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment