CSC148H/A48H exercise — week 3
Important:
- Work individually, get help from me or your TA if you are stuck.
- Please submit your solution (in Lights.py) to the online submit page. Do not give your solution to
your classmates. Doing so robs them of the chance to learn, so you really would not be helping them.
Light Switch Problem
I have a board of Lights, numbered 0,1,2,...,1023.
Each Light can be either on or off. All Lights are initially off.
Step 1:
I flip all of the Lights starting at 0.
At this point, all of the Lights are on.
Step 2:
I flip every second Light, starting at 0.
At this point, Lights 0,2,4,6,8,... are off.
Lights 1,3,5,7,9,... are still on.
Step 3:
I flip every third Light, starting at 0.
So I flip Lights 0,3,6,9,12,...
that is, if a Light is on, I flip it to off.
If a Light is off, I flip it on.
...
Step 1023:
I flip every 1023'rd Light, starting at 0.
So I flip 0 and 1023.
Question: At this point, which Lights are on and which are off?
To solve this puzzle, build a python program (in file Lights.py) with classes
- Light with a constructor
__init__(self), and methods turn_on(self), turn_off(self), flip(self) and __str__(self).
ls=Light() # creates a Light which is off
ls.turn_on() # turns the switch on
ls.turn_on() # turns the switch on (it already was)
ls.flip() # flips the switch (now its off)
ls.flip() # flips the switch (now its on)
ls.flip() # flips the switch (now its off)
print(ls)
- LightBoard with a constructor
__init__(self, num_lights), and methods step(self,i), all_steps(self) and __str__(self).
lbA=LightBoard(20) # creates a LightBoard with 20 Lights
lbA.all_steps() # run through steps 1, 2, ..., 19
print(lbA) # print out each light switch and whether it is on or off
lbB=LightBoard(30) # creates a LightBoard with 30 Lights
lbB.all_steps() # run through steps 1, 2, ..., 29
print(lbB) # print out each light switch and whether it is on or off
lb=LightBoard(1024) # creates a LightBoard with 1024 Lights (0,...,1023)
lb.all_steps() # run through steps 1, 2, ..., 1023
print(lb) # did you learn anything? Which lights are on/off in the following...why?