Count the number of times a Bulb switches its state | Python program for the above approach ; Function to find the number of times a bulb switches its state ; count of 1 's ; Traverse the array ; update the array ; update the status of bulb ; Traverse the array Q [ ] ; stores previous state of the bulb ; Toggle the switch and update the count of 1 's ; if the bulb switches state ; Return count ; Input ; Queries ; Function call to find number of times the bulb toggles
import math NEW_LINE def solve ( A , n , Q , q ) : NEW_LINE INDENT one = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( A [ i ] == 1 ) : NEW_LINE INDENT one += 1 NEW_LINE DEDENT DEDENT glows = 0 NEW_LINE count = 0 NEW_LINE if ( one >= int ( math . ceil ( n / 2 ) ) ) : NEW_LINE INDENT glows = 1 NEW_LINE DEDENT for i in range ( 0 , q ) : NEW_LINE INDENT prev = glows NEW_LINE if ( A [ Q [ i ] - 1 ] == 1 ) : NEW_LINE INDENT one -= 1 NEW_LINE DEDENT if ( A [ Q [ i ] - 1 ] == 0 ) : NEW_LINE INDENT one += 1 NEW_LINE DEDENT A [ Q [ i ] - 1 ] ^= 1 NEW_LINE if ( one >= int ( math . ceil ( n / 2.0 ) ) ) : NEW_LINE INDENT glows = 1 NEW_LINE DEDENT else : NEW_LINE INDENT glows = 0 NEW_LINE DEDENT if ( prev != glows ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT n = 3 NEW_LINE arr = [ 1 , 1 , 0 ] NEW_LINE q = 3 NEW_LINE Q = [ 3 , 2 , 1 ] NEW_LINE print ( solve ( arr , n , Q , q ) ) NEW_LINE