# Python NumPy For Your Grandma - 6.5 Challenge: Table Tennis

Contents

## Setup

After a series of poor life choices, you find yourself managing a recreational table tennis league. There are 10 participants and in an effort to make the first round of matchups as exciting as possible, you develop a model that predicts the score difference for every possible pair of players. That is, you produce a 10x10 matrix where (i,j) represents your prediction for player i’s score minus player j’s score if they were to compete. Given this matrix, determine the “best” matchups for round one - the matchups that minimize the sum of squared point differentials.

``````import numpy as np

generator = np.random.default_rng(0)
score_diffs = np.round(generator.uniform(low=-15, high=15, size=(10,10)), 2)
np.fill_diagonal(score_diffs, np.nan)
score_diffs[np.triu_indices(10, k=1)] = -score_diffs[np.tril_indices(10, k=-1)]
print(score_diffs)
## [[   nan  -9.48  14.15  11.27  -5.65   3.33  10.95  -2.15   5.34  -2.83]
##  [  9.48    nan   4.86  -8.61   7.82 -11.29  13.24   4.92   2.86   9.04]
##  [-14.15 -11.27    nan  12.28  -2.41   6.04  -5.16  -3.87 -12.81   1.79]
##  [  5.65  -3.33 -10.95    nan -13.64   0.     2.24  -3.61  -7.73   0.08]
##  [  2.15  -5.34   2.83  -4.86    nan  -0.88  -8.57   2.56  -7.03  -6.33]
##  [  8.61  -7.82  11.29 -13.24  -4.92    nan -12.96 -12.82 -14.04  14.56]
##  [ -2.86  -9.04 -12.28   2.41  -6.04   5.16    nan -10.91 -14.44 -13.72]
##  [  3.87  12.81  -1.79  13.64  -0.    -2.24   3.61    nan  10.54 -14.18]
##  [  7.73  -0.08   0.88   8.57  -2.56   7.03   6.33  12.96    nan -11.7 ]
##  [ 12.82  14.04 -14.56  10.91  14.44  13.72 -10.54  14.18  11.7     nan]]
``````

## Solution

``````# How to represent all possible schedules?
# [(0,1), (2,3), (4,5), (6,7), (8,9)]
# [(0,1), (2,3), (4,5), (6,8), (7,9)]
# [(0,1), (2,3), (4,5), (6,9), (7,8)]

# Consider array with [0,1, 2,3, 4,5, 6,7, 8,9]
# Consider all possible permutations
# Pick out permutations where the value at position 0 is less than the value at position 1, val @ 2 < val @ 3, ...

# Build all permutations of [0, 1, 2, .. 9]
from itertools import permutations
perms = np.array(list(permutations([0,1,2,3,4,5,6,7,8,9])))

# Partition into two matrices representing player 1 and player 2
p1 = perms[:, [0,2,4,6,8]]
p2 = perms[:, [1,3,5,7,9]]

# Only retain matchups where player 1 < player 2
keeps = np.all(p1 < p2, axis=1)
p1 = p1[keeps]
p2 = p2[keeps]

# Build a matrix where (i,j) gives the expected point differential
# for the jth pairing in the ith schedule
point_diffs = score_diffs[p1, p2]

# Calculate sum of squared point differentials
schedule_scores = np.sum(point_diffs**2, axis=1)

# Identify the best schedule
best_idx = np.argmin(schedule_scores)
best_schedule = np.vstack((p1[best_idx], p2[best_idx]))

print(best_schedule)
## [[0 3 1 2 4]
##  [7 6 8 9 5]]
``````