Skip to content

Instantly share code, notes, and snippets.

@whunter
Last active August 29, 2015 14:15
Show Gist options
  • Save whunter/217af478a1399f8d373d to your computer and use it in GitHub Desktop.
Save whunter/217af478a1399f8d373d to your computer and use it in GitHub Desktop.
Figure out which lights would remain on given the scenario described by Click and Clack here: http://www.cartalk.com/content/hall-20000-lights?question
#!/usr/bin/python
import sys
# @author Lee Hunter
# @email wleehunter@gmail.com
# @prerequisites: python version 2.5 or higher (I think)
# @usage: python lightspuzzler.py <number_of_lights>
# @example: python lightspuzzler.py 20000 (This would give the results from the actual question. It will also take forever)
# short, messy script to calculate which lights would remain on given the scenario described by Click and Clack.
# http://www.cartalk.com/content/hall-20000-lights?question
class LightsPuzzler:
lights = []
# Create a list of lights, all initially off.
def init(self, numlights):
for i in range(0, numlights + 1):
self.lights.append(0)
# Go through the scenario described, pulling a LOT of strings.
def pullstrings(self):
# Go through each of the people
for multiplier in range(1, len(self.lights)):
print 'Guy #' + str(multiplier) + ' is pulling strings now.'
# and for each person pull all of the appropriate light strings
for idx in range(1, len(self.lights)):
self.pull(idx * multiplier)
# Set the light to it's opposite state. If it's on(1), turn it off(0). If it's off(0), turn it on(1)
def pull(self, index):
if index < len(self.lights):
self.lights[index] = 0 if self.lights[index] == 1 else 1
# Go through all of the lights after all of the strings have been pulled.
# If the light is still on(1) add it to the results list.
# Write it all to the results file
def report(self):
resultstring = "The lights that would remain on: "
for i in range(1, len(self.lights)):
if self.lights[i] == 1:
resultstring += str(i) + ", "
f = open('results.txt','w')
f.write(resultstring[:-2])
f.close()
print ''
print 'WHEW!!! ...okay, they should all be done pulling strings now.'
print 'You can find the results in results.txt which should be located in the same folder as this script.'
def main(numlights):
puzzler = LightsPuzzler()
puzzler.init(int(numlights))
puzzler.pullstrings()
puzzler.report()
if __name__ == "__main__":
main(sys.argv[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment