gpt4 book ai didi

python - 在for循环中递增

转载 作者:太空宇宙 更新时间:2023-11-04 03:25:51 24 4
gpt4 key购买 nike

所以我的问题是这个没有正确递增...每次运行此循环时我都尝试使用 int "step"to + 1 但它什么也没做。这是为什么?此外,当我打印(步骤)时,它只加起来为 337。它并没有像我想的那样达到完整的 1000,我也问过它。我该如何正确执行此操作?

lockers = []

step = 3

locker = 0

while len(lockers) <= 1000:
lockers.append(1)

for i in range(0, len(lockers)):
lockers[i] = 0

for i in range(0, len(lockers), 2):
lockers[i] = 1

for i in range(0, len(lockers), step):
if lockers[i] == 0:
lockers [i] = 1
else:
lockers[i] = 0

step += 1


print(lockers)

最佳答案

range 给你一个可迭代的对象:

>>> range(10,20 , 2)
range(10, 20, 2)
>>> list(range(10,20 , 2))
[10, 12, 14, 16, 18]

其中的值在调用返回后立即完全确定,并且不会在每次循环时都重新计算。您的 step 只增加到 337,因为您为对象 range(0, 1000, 3) 中的每个元素递增一次,它有 334 个项目,而不是 1000:

>>> len(range(0,1000,3))
334

要获得类似于 range 但推进 step 的东西,您需要编写自己的生成器:

def advancing_range(start, stop, step):
''' Like range(start, stop, step) except that step is incremented
between each value
'''
while start < stop:
yield start
start += step
step += 1

然后您可以执行 for i in advanced_range(0, 1000, 3):,它将按您的预期工作。

但这是一件很奇怪的事情,想要去做。从你的变量名来看,我猜你正在编码 locker problem ,它说:

A new high school has just been completed. There are 1,000 lockersin the school and they have been numbered from 1 through 1,000.During recess (remember this is a fictional problem), the studentsdecide to try an experiment. When recess is over each student willwalk into the school one at a time. The first student will open allof the locker doors. The second student will close all of the lockerdoors with even numbers. The third student will change all of thelocker doors that are multiples of 3 (change means closing lockersthat are open, and opening lockers that are closed.) The fourthstudent will change the position of all locker doors numbered withmultiples of four and so on. After 1,000 students have entered theschool, which locker doors will be open, and why?

但是推进范围逻辑更像是“第一个学生打开第一个储物柜,然后第二个学生打开第二个储物柜,然后第三个学生打开第三个储物柜……”。您想每次影响多个储物柜,但要间隔得更远。本质上,您希望将前两个循环再复制并粘贴 998 次,每次都提高一个 step。当然,您可以做得比复制和粘贴更好,这似乎需要两个嵌套循环,其中外部循环推进内部循环使用的 step。看起来像这样:

for step in range(1, len(lockers)):
for i in range(step, len(lockers), step):

通过使用 bool 值代替 10 来简化您的其他逻辑,整个程序如下所示:

lockers = [True] * 1000

for step in range(1, len(lockers)):
for i in range(step, len(lockers), step):
lockers[i] = not lockers[i]

print(sum(lockers))

打印出打开的储物柜数量为969。

关于python - 在for循环中递增,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33050384/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com