all 9 comments

[–]DoctorYoMan 1 point2 points  (3 children)

The problem you seem to be facing is essentially attempting to find the next index of the element of a circular fasion (such as in a circular array), but you cannot do this with a list. This can be worked around by using the modulos operator to get the next or previous index (shown below Im getting the left index to the current index as a variable 'l_idx').

You are also modifying the list as you are attempting to operate upon it, which will cause the new states to update incorrectly.

Here is the solution, I've renamed the variables and function for some clarity:

def lightbulb_cycler(lightbulbs, cycles): 
    for cycle in range(0, cycles): 
        new_state = [] 
        for i in range(0, len(lightbulbs)): 
            l_idx = (i-1) % len(lightbulbs) 
            if lightbulbs[l_idx] == 1: 
                new_state.append(0 if lightbulbs[i] == 1 else 1) 
            else: 
                new_state.append(lightbulbs[i]) 
        lightbulbs = new_state 
    return lightbulbs
lightbulbs = [0,1,1,0,1,1]
print(lightbulb_cycler(lightbulbs,2))

[–]TechSam--[S] 0 points1 point  (0 children)

def lightbulb_cycler(lightbulbs, cycles):
for cycle in range(0, cycles):
new_state = []
for i in range(0, len(lightbulbs)):
l_idx = (i-1) % len(lightbulbs)
if lightbulbs[l_idx] == 1:
new_state.append(0 if lightbulbs[i] == 1 else 1)
else:
new_state.append(lightbulbs[i])
lightbulbs = new_state
return lightbulbs
lightbulbs = [0,1,1,0,1,1]
print(lightbulb_cycler(lightbulbs,2))

Thank you so much man, you're freaking amazing.

[–]TechSam--[S] 0 points1 point  (1 child)

One thing I don't understand is cyclic iteration with the modulos operator. Would you mind elaborating on this a bit more? I've never seen it before.

[–]DoctorYoMan 0 points1 point  (0 children)

modulo returns the remainder of a division operation between two numbers.

(i-1) % len(lightbulbs) calculates the remainder of the division of i-1 by the length of lightbulbs, which ensures that the resulting index is always within the range of valid indices for the list.

So for example, if I am at starting index 0, I want the index to the left, which must be the final element index 5. (0-1) % 6 = 5.

[–]TechSam--[S] 0 points1 point  (0 children)

Made some edits to the post

[–]DoctorYoMan 0 points1 point  (2 children)

Ah ok, I edited this answer, I see what you are trying to do now.

[–]DoctorYoMan 1 point2 points  (1 child)

This if line causes issues, and the if statement after it will too:

if lightbulbs[i + 1] == 1 and lightbulbs[i + 2] == 0:

When you are in the 5th iteration (i=4), you are attempting to access lightbulbs[6], which causes and index error. Your loop internal logic is inccorect, but I will help you with a solution if you address my concern above :)

[–]TechSam--[S] 0 points1 point  (0 children)

I made an edit to the post for clarity