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

标签 python python-3.x

有任务:

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/

相关文章:

python-3.x - Python 如何知道 π 的所有这些变体都是相同的变量名?

python 惰性变量?或者,延迟昂贵的计算

python - 重新排序列表理解中的语句时出现 NameError

python - 如何用python实现构建变体?

python - 在 Debian 上获得 Python 3 Mechanize 的最简单方法是什么?

arrays - Codefights aresimilar Challenge in python3

python - 确定循环中的第一次出现

python - Apache Beam 对 ParDo 行为的解释

python - 如何在 Markdown 标题中写入 Python 字符串变量?

python - Groupby 以及 value_counts 的工作原理