- 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 check first player can win by reaching total sum to target in Python
Suppose we have two numbers k and target. Now consider Amal and Bimal are playing a game. In each round Amal picks a number from 1 to k to add to the total score that initially starts from 0. Whoever crosses the total to target wins. Amal always plays first, we have to check whether he can force a win if both of them plays optimally.
So, if the input is like k = 5 target = 10, then the output will be True, as if Amal picks 4 first, then whether Bimal picks 1, 2, ..., or 5, Amal can always reach 10 by picking 5 next.
To solve this, we will follow these steps −
- if target % (k + 1) is not 0, then
- return true
- otherwise
- return false
Example
Let us see the following implementation to get better understanding −
def solve(k, target): return target % (k + 1) != 0 k = 5 target = 10 print(solve(k, target))
Input
5, 10
Output
True
Advertisements