Skip to content

Instantly share code, notes, and snippets.

@KMurphs
Last active February 20, 2022 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KMurphs/68a5566c7078df10fe479a32820f2be6 to your computer and use it in GitHub Desktop.
Save KMurphs/68a5566c7078df10fe479a32820f2be6 to your computer and use it in GitHub Desktop.
For the Priority Queue Medium Article
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