Skip to content

Instantly share code, notes, and snippets.

@adamashton
Last active December 15, 2015 09:18
Show Gist options
  • Save adamashton/0313610fedce9a4526b6 to your computer and use it in GitHub Desktop.
Save adamashton/0313610fedce9a4526b6 to your computer and use it in GitHub Desktop.
Calculate the number of lights to use for certain quantities.
delta = 0.01
class Light:
def __init__(self, quantity, priority):
self.quantity = quantity
self.priority = priority
self.n_on = 0
def _do_priority_magic(n_lights, lights):
if n_lights < len(lights):
raise Exception('Not enough lights for scene')
sumQuantities = sum([l.quantity for l in lights])
if abs(1 - sumQuantities) > delta:
# scale quantities to sum to 1
multiplier = 1 + abs(1 - sumQuantities)
for l in lights:
l.quantity *= multiplier
for l in lights:
l.n_on = iround(l.quantity * n_lights)
light_count = sum([r.n_on for r in lights])
while light_count > n_lights:
# remove a light from the lowest priority item
lowestPriority = sorted(lights, key=lambda x: x.priority)[0]
lowestPriority.n_on -= 1
light_count = sum([l.n_on for l in lights])
while light_count < n_lights:
# add a light to the highest priority item
highestPriority = sorted(lights, key=lambda x: x.priority, reverse=True)[0]
highestPriority.n_on += 1
light_count = sum([l.n_on for l in lights])
return lights
def iround(x):
"""iround(number) -> integer
Round a number to the nearest integer."""
y = round(x) - .5
return int(y) + (y > 0)
l1 = Light(0.5, 1)
l2 = Light(0.5, 2)
lights = [l1, l2]
_do_priority_magic(5, lights)
print([l.n_on for l in lights])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment