Mic*_*oun 2 python list python-3.x
我正在尝试通过编辑列表来解决问题,该列表可以跟踪学校中已打开和关闭的储物柜,我得到的代码如下:
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)
Run Code Online (Sandbox Code Playgroud)
代码运行平稳,没有任何错误,但是返回的值为100。我已经对每个变量进行了故障排除,并且都对其进行了修改。我的结论是问题出在线中
y[x] = "C"
Run Code Online (Sandbox Code Playgroud)
和
y[x] = "C"
Run Code Online (Sandbox Code Playgroud)
这些行之后的列表完全没有变化。
我添加了w以便不在len(y)range函数内部使用,并且我无法使用
for i in y
Run Code Online (Sandbox Code Playgroud)
因为我需要在循环中的项目之间迈出一步y。
我希望能够在循环内修改列表中的项目或使用解决方法...
您的代码还有其他一些地方可以简化,但是真正的问题在for循环内:
if y[x] == "O":
y[x] = "C"
if y[x] == "C":
y[x] = "O"
Run Code Online (Sandbox Code Playgroud)
如果储物柜是打开的,则将其设置为关闭。然后,立即if执行下一条语句,将其设置回打开状态。因此,您似乎并没有改变y。将第二条if语句更改为一条elif语句:
if y[x] == "O":
y[x] = "C"
elif y[x] == "C":
y[x] = "O"
Run Code Online (Sandbox Code Playgroud)
这应该可以解决您的问题。
现在,这是独立且不必要的,但将大大简化您的代码。尝试以下操作(使用布尔状态而不是字母):
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)
Run Code Online (Sandbox Code Playgroud)