Skip to content

Instantly share code, notes, and snippets.

@thousandlemons
Last active January 4, 2017 12:12
Show Gist options
  • Save thousandlemons/69613e92a0d2212a9b1311adafb65393 to your computer and use it in GitHub Desktop.
Save thousandlemons/69613e92a0d2212a9b1311adafb65393 to your computer and use it in GitHub Desktop.
The Light Bulb Problem
{
"off": 60,
"on": 90,
"size": 150
}
import json
class LightBulb(object):
on = None
def __init__(self, on=False):
self.on = on
def turn_on(self):
self.on = True
def turn_off(self):
self.on = False
def flip_switch(self):
self.on = not self.on
class Bus(object):
light_bulbs = []
def __init__(self, size):
for i in range(size):
self.light_bulbs.append(LightBulb(on=True))
def analyze(self):
on_count = 0
off_count = 0
for lb in self.light_bulbs:
if lb.on:
on_count += 1
else:
off_count += 1
return {
'size': len(self.light_bulbs),
'on': on_count,
'off': off_count
}
def flip_if_index_is_a_multiple_of(self, divisor):
for index, light_bulb in enumerate(self.light_bulbs):
human_readable_index = index + 1
if human_readable_index % divisor == 0:
light_bulb.flip_switch()
def main():
bus = Bus(size=150)
bus.flip_if_index_is_a_multiple_of(divisor=3)
bus.flip_if_index_is_a_multiple_of(divisor=5)
analysis = bus.analyze()
with open('result.json', 'w+') as file:
file.write(json.dumps(analysis, indent=4, sort_keys=True))
if __name__ == '__main__':
main()

The Light Bulb Problem

There are 150 light bulbs each with a flip switch, indexed from 1 to 150. Initially, they are all on.

First, you look at each of the light bulbs sequentially, and flip the switch if its index number is divisible by 3.

Then, you iterate through all the light bulbs again, but this time you only flip the switch if the index number is divisible by 5.

How many light bulbs are on now?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment