python - 关灯算法

标签 python algorithm

我正在用 Python 创建关闭算法。我想包括数字矩阵。它说想象一排 n 盏灯,编号为 1 到 n,可以在特定条件下打开或关闭。第一盏灯可以随时打开或关闭。只有当前面的灯亮并且其他灯都熄灭时,其他灯才能打开或关闭。如果一开始所有的灯都亮着,你怎么能把它们都关掉呢?对于编号为1到3的三盏灯,您可以按照以下步骤操作,其中i表示灯亮,0表示灯灭。

  • 111 3 盏灯亮着
  • 011 关闭灯 1
  • 010 关灯 3
  • 110 打开灯1
  • 100 关灯2
  • 000 关灯1

如何在我的程序中包含数字矩阵?

到目前为止,这是我的代码:

def turnOff(n):
    #if number of lights is less than one
    if (n < 1):
        return
    #if number of lights is greater or equal to one
    if (n == 1):
        print("Turn off light", n)
    else:
        if(n > 2):
            turnOff(n - 2)
            print("Turn off light", n)
        if(n > 2):
            turnOn(n - 2)
            turnOff(n - 1)


def turnOn(n):
    # if number of lights is less than one
    if(n < 1):
        return
    # if number of lights is 1
    if(n == 1):
        print("Turn on light", n)
    else:
        turnOn(n - 1)
        if(n > 2):
           turnOff(n - 2)
           print("Turn on light", n)
        if(n > 2):
            # call method
            turnOn(n - 2)


def main():
    n = int(input("Please enter a number of lights: "))
    print()
    print(turnOn(n))
    # print("Number of steps", count)


if __name__ == "__main__":
    main()

请输入灯的个数:3

  • 打开灯 1
  • 关掉灯 1
  • 打开灯 3
  • 打开灯 1

这是我得到的输出。我想添加一个矩阵。

最佳答案

您必须创建一个列表变量来保存灯光的状态。当您打开或关闭灯时,您将更新列表中的相应条目。您可以使用此列表来显示当前状态并验证哪些灯可以切换。

numberOfLights = int(input("Please enter a number of lights: "))
lights         = [1] * numberOfLights
while 1 in lights:    
    lightIndex = int(input(f"{lights} toggle which light ? ")) - 1
    if lightIndex > 0 and lights.index(1) != lightIndex-1:
        print("You cannot toggle that light")
        continue
    lights[lightIndex] = 1 - lights[lightIndex]
print(f"{lights} success !!")

请注意,列表索引从零开始(而不是 1)。这就是用户输入的灯号减1的原因

示例游戏:

Please enter a number of lights: 4
[1, 1, 1, 1] toggle which light ? 1
[0, 1, 1, 1] toggle which light ? 2
You cannot toggle that light
[0, 1, 1, 1] toggle which light ? 1
[1, 1, 1, 1] toggle which light ? 2
[1, 0, 1, 1] toggle which light ? 1
[0, 0, 1, 1] toggle which light ? 4
[0, 0, 1, 0] toggle which light ? 2
You cannot toggle that light
[0, 0, 1, 0] toggle which light ? 1
[1, 0, 1, 0] toggle which light ? 2
[1, 1, 1, 0] toggle which light ? 1
[0, 1, 1, 0] toggle which light ? 3
[0, 1, 0, 0] toggle which light ? 1
[1, 1, 0, 0] toggle which light ? 2
[1, 0, 0, 0] toggle which light ? 1
[0, 0, 0, 0] success !!

关于python - 关灯算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55433328/

相关文章:

python - 使用 Pika 客户端轮询 RabbitMQ 消息

python - 在python中解析大文件的多行,将它们存储在列表中

python - Tensorflow:噪声对比估计语言模型

c# - 计算一周内工作的天数而不循环?

php - 词典搜索

查找重叠线段的算法

python - 打印与标准错误

java - 在 Java 中使用图论算法的面向对象方法是否比基于一般数组的操作更快?

algorithm - 使用桶算法排序

python - 如何使用 Google Chrome 和 Selenium 从 headless 模式切换到正常模式?