Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to count number of matches played in tournament in Python
Suppose we have a number n representing the number of teams in a tournament. The tournament follows specific rules to determine matches and winners ?
If the number of teams is even, each team gets paired with another team. A total of (n/2) matches are played, and (n/2) winner teams advance to the next round.
If the number of teams is odd, one team randomly advances to the next round without playing. The remaining teams get paired, so (n-1)/2 matches are played, and (n-1)/2 + 1 teams advance as winners.
We need to find the total number of matches played until we get the final winner.
Example Walkthrough
If n = 10, the output will be 9 because ?
Round 1: 10 teams ? 5 matches ? 5 winners
Round 2: 5 teams ? 1 advances, 4 play ? 2 matches ? 3 winners
Round 3: 3 teams ? 1 advances, 2 play ? 1 match ? 2 winners
Round 4: 2 teams ? 1 match ? 1 final winner
Total matches: 5 + 2 + 1 + 1 = 9
Algorithm Steps
To solve this problem, we follow these steps ?
Initialize ans = 0 to count total matches
-
While n is not equal to 1, do:
Calculate matches played: f = n // 2
Find remaining team: remainder = n % 2
Add matches to total: ans += f
Update teams for next round: n = f + remainder
Return total matches
Implementation
def solve(n):
ans = 0
while n != 1:
f = n // 2
remainder = n % 2
ans += f
n = f + remainder
return ans
# Test with example
n = 10
result = solve(n)
print(f"Number of teams: {n}")
print(f"Total matches played: {result}")
Number of teams: 10 Total matches played: 9
Alternative Approach
There's also a mathematical insight: in any single-elimination tournament, we need to eliminate n-1 teams to find one winner. Each match eliminates exactly one team, so the answer is always n-1 ?
def solve_optimized(n):
return n - 1
# Test both approaches
test_cases = [10, 7, 16, 1]
for teams in test_cases:
matches1 = solve(teams)
matches2 = solve_optimized(teams)
print(f"Teams: {teams}, Method 1: {matches1}, Method 2: {matches2}")
Teams: 10, Method 1: 9, Method 2: 9 Teams: 7, Method 1: 6, Method 2: 6 Teams: 16, Method 1: 15, Method 2: 15 Teams: 1, Method 1: 0, Method 2: 0
Conclusion
Both approaches work correctly, but the optimized solution reveals that any single-elimination tournament with n teams requires exactly n-1 matches. The simulation approach helps understand the tournament flow, while the mathematical approach provides immediate results.
