gpt4 book ai didi

python - 关灯算法

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:37:32 29 4
gpt4 key购买 nike

我正在用 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/

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