[英]How to turn off LED lights/flashlight on camera in Python OpenCV
[英]Turn Off the lights algorithm
我在Python中創建turnOff算法。 我想要包括數字矩陣。 它描述了一排n個燈,編號為1到n,可以在某些條件下打開或關閉。 第一盞燈可以隨時打開或關閉。 只有當前一盞燈亮起且其前所有其他燈熄滅時,才能打開或關閉其他每盞燈。 如果所有燈都是最初打開的,那么如何將它們全部關閉? 對於編號為1到3的三個燈,您可以執行以下步驟,其中i表示燈亮,0表示燈熄滅。
我如何在程序中包含數字矩陣?
到目前為止,這是我的代碼:
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
以下是我作為輸出得到的東西。 我想添加一個矩陣。
您必須創建一個列表變量來保存燈光的狀態。 當您打開或關閉燈光時,您將更新列表中的相應條目。 您可以使用此列表顯示當前狀態並驗證可以切換的燈光。
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 !!
考慮用二進制編寫的數字。 觀察比特在遞減時如何變化,並觀察相鄰比特之間的差異如何變化。
x bits of x bits of x XORed with adjacent higher bit
== =========== ===========================================
15 1111 1000
14 1110 1001
13 1101 1011
12 1100 1010
11 1011 1110
10 1010 1111 <--these bits are lights. Here they are all on
9 1001 1101
8 1000 1100
... bla bla bla ...
1 0001 0001
0 0000 0000
請注意,從最右邊的位開始,最后一列位遵循您的規則!
在任何時候你都有兩個選擇 - 你可以翻轉第一個燈,或者你可以找到第一個燈並翻轉下一個燈。 兩個選項都對應於x的增量或減量。
設G(x)是通過將x的每個位與第二個最高位進行異或運算得到的數。 (G,因為它是格雷碼: https : //en.wikipedia.org/wiki/Gray_code )
現在,回答關於如何從一個燈序列到另一個燈序列的所有問題變得非常容易。 如果你想從所有燈開始並關閉它們,只需:
從x = 10開始,使G(x)= 15 (二進制1111)
將它減少到0.那當然需要10步。
如果你想知道燈是什么的,可以隨時寫出G(x)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.