
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count Matches Played in Tournament using Python
Suppose we have a number n. So there are n number of teams in a tournament that has some rules −
If the number of teams is even currently, then each team gets merged with another team. And a total of (n/2) matches are played, from them (n/2) winner teams will move to the next round.
If the number of teams is odd, then one team randomly moved in the tournament, and the rest gets merged. So a total of (n-1)/2 matches are played, and (n-1)/2+1 teams are moved to the next round as winner.
We have to find total number of matches are played so that we get the final winner.
So, if the input is like n = 10, then the output will be 9 because
Initially there will be 5-5 division, among them 5 will be qualified
Now pass one team to the game and divide 2-2 teams, so 3 will be qualified
Now pass one team to the game and divide 1-1 teams, so 2 will be qualified
Divide 1-1 and one will be qualified as winner.
To solve this, we will follow these steps −
ans := 0
-
while n is not same as 1, do
f := floor of (n/2)
remainder := n mod 2
ans := ans + f
n := f + remainder
return ans
Example (Python)
Let us see the following implementation to get better understanding −
def solve(n): ans = 0 while n != 1: f = n//2 remainder = n % 2 ans += f n = f + remainder return ans n = 10 print(solve(n))
Input
10
Output
9