gpt4 book ai didi

python - 使用类解决光之谜,但翻转困难。 (Python 3)

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

有任务:

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?



这是我的代码:

class Light:

def __init__(self):
self.state = 'OFF'

def turn_on(self):
self.state = 'ON'

def turn_off(self):
self.state = 'OFF'

def flip(self):
if self.state == 'OFF':
self.state = 'ON'
else:
self.state = 'OFF'

def __str__(self):
return str(self.state)


class LightBoard:

def __init__(self, num_lights):
self.light = [Light()] * num_lights

def step(self,i):
for element in self.light:
if self.light.index(element) % i == 0:
self.light[self.light.index(element)] = self.light[self.light.index(element)].flip()

def all_steps(self):
i = 0
while i != len(self.light):
self.light = self.light.step(self.light, i)
i += 1

def __str__(self):
return str(self.light)



我使用了Python可视化工具,发现LightBoard中的all_steps不起作用。

AttributeError: 'list' object has no attribute 'step'

我无法纠正它。
请帮助纠正/对我的代码发表评论。谢谢!

最佳答案

有一个问题

    self.light = [Light()] * num_lights

这需要更改为

    self.light = [Light() for _ in range(num_lights)]

否则,self.light 包含对同一 Light 对象的引用。

还有其他问题,包括:

  1. 您需要两层循环,而不仅仅是一层。
  2. 以下内容有几个错误:self.light = self.light.step(self.light, i)。一个问题是您在 self.light 上调用 step,这是一个列表。

附注你必须为此编写一个程序吗?这是使用笔和纸可以相当容易解决的问题之一。

关于python - 使用类解决光之谜,但翻转困难。 (Python 3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14537477/

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