- 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
Check if it is possible to get back to 12 O-clock only by adding or subtracting given seconds in Python
Suppose we have an array of n different second values. We have to check whether it is possible to start from 12'O clock and go back to 12 by only adding or subtracting the given seconds or not. We can use all given seconds exactly once, we can either add seconds or subtract it.
So, if the input is like seconds = [40,90,50], then the output will be True as it can add 40 then subtract 90 then again add 50.
To solve this, we will follow these steps −
- size := 2^(length of seconds array)
- for c in range 0 to size - 1, do
- add := 0
- for j in range 0 to size of seconds - 1, do
- if c AND (2^j) is non-zero, then
- add := add + seconds[j]
- otherwise,
- add := add - seconds[j]
- if c AND (2^j) is non-zero, then
- if add is divisible by (24 * 60), then
- return True
- return False
Example
Let us see the following implementation to get better understanding −
def solve(seconds): size = 2**len(seconds) for c in range(size): add = 0 for j in range(len(seconds)) : if c & (1 << j): add += seconds[j] else: add -= seconds[j] if add % (24 * 60) == 0: return True return False seconds = [40,90,50] print(solve(seconds))
Input
[40,90,50]
Output
True
Advertisements