Michel Chalfoun
Michel Chalfoun

Reputation: 105

Can't edit list items inside loop

I am trying to solve a problem by editing a list that keeps track of closed and open lockers in a school, the code I got to is the following:

y = list()
lockers = 100
students = 100
s = 2
i = 0
while i < lockers:
    y.append("O")
    i = i + 1
w = len(y)
while s <= students:
    for x in range(s, w, s):
        if y[x] == "O":
            y[x] = "C"
        if y[x] == "C":
            y[x] = "O"
    s = s + 1
openLockers = y.count("O")
print(openLockers)

The code is running smoothly without any errors but returns a value of 100. I have troubleshooted every variable and they all are being modified. I have concluded that the problems lies in the lines

y[x] = "C"

and

y[x] = "C"

The list is not changing at all after those lines.

I have added w in order to not use len(y) inside the range function and I cannot use

for i in y

because I need to a step between the items in the loop y.

I want to be able to modify the items in the list inside the loop or use a workaround...

Upvotes: 2

Views: 177

Answers (2)

iz_
iz_

Reputation: 16613

Your code has a few other places where it can be simplified, but your real problem is here within the for loop:

if y[x] == "O":
    y[x] = "C"
if y[x] == "C":
    y[x] = "O"

If the locker is open, you set it to closed. Then, immediately, the next if statement executes, setting it back to open. Thus, you seemingly don't change y. Change the second if statement to an elif statement:

if y[x] == "O":
    y[x] = "C"
elif y[x] == "C":
    y[x] = "O"

This should fix your problem.


Now, this is separate and unnecessary but will simplify your code quite a bit. Try this (uses Boolean state instead of letters):

lockers = 100
students = 100
y = [False] * lockers

for s in range(2, students):
    for x in range(s, lockers, s):
        y[x] = not y[x]

openLockers = y.count(False)
print(openLockers)

Upvotes: 5

lmiguelvargasf
lmiguelvargasf

Reputation: 69785

Assuming you have just two possible values for y[x] which are 'O' and 'X', you can use the following simplification in your code:

y[x] = "C" if y[x] == "O" else "O"

Upvotes: 1

Related Questions