Program to make a bulb switcher using binary string using Python

PythonServer Side ProgrammingProgramming

Suppose we have n bulbs in a room, these bulbs are numbered from 0 to n-1. We have to arrange them in a row from left to right. Initially, all the bulbs are turned off (0-state). We have to get the configuration represented by given target array 't' where t[i] is '1' if the ith bulb is on and '0' if it is off. We also have a switch to flip the state of the bulb. And flipping operation is defined as follows −

  • Select any bulb index i.

  • Flip each bulb from index i to index n - 1.

We have to find the minimum number of flips required to form target.

So, if the input is like t = "0101", then the output will be 3, if we start from second bulb, then next configuration will be "0111", then from third, it will be "0100", then flip last bulb to make it "0101"

To solve this, we will follow these steps −

  • count := 0

  • x := '0'

  • for each i in t, do

    • if i is not same as x, then

      • count := count + 1

      • x := i

  • return count

Let us see the following implementation to get better understanding −


 Live Demo

def solve(t):
   count = 0
   x = '0'
   for i in t:
      if i != x:
         count += 1
         x = i
   return count
t = "0101"




Published on 28-May-2021 12:42:12