- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to make a bulb switcher using binary string using Python
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 −
Example
def solve(t): count = 0 x = '0' for i in t: if i != x: count += 1 x = i return count t = "0101" print(solve(t))
Input
"0101"
Output
3