DEV Community

Discussion on: Daily Challenge #153 - Horse Race Gamble

Collapse
 
dangerontheranger profile image
Kermit Alexander II • Edited

The word "combinations" being used here provides us with a good jumping-off point to figure out the solution - combinatorics! We can calculate the n choose k/binomial coefficient for the horses, where n is the total number of horses, and k is equal to 3, since we're looking for 3 horses (gold, silver, and bronze winners). From there, we need to take into account that ordering - which horse won which position - matters to us; mathematical combinations are sets in which order doesn't normally matter. We'll need permutations for that part.

So, knowing that the number of permutations for a set of n elements is equal to n!, we can multiply the result of our n choose k by 6 (which is just a shorthand for multiplying by 3!, as 3! = 6). Putting that all together with a little bit of error checking, we have the following short Python solution:

#!/usr/bin/env python3
import math


def nchoosek(n, k):
    n_fac = math.factorial(n)
    denominator = math.factorial(k) * math.factorial(n - k)
    return n_fac / denominator


def horses(num_horses):
    try:
        # check for non-integer but still numerical input
        if int(num_horses) != num_horses:
            return None
    except ValueError:
        # check for non-numerical input
        return None
    if num_horses <= 3:
        return num_horses
    return int(nchoosek(num_horses, 3) * 6)


if __name__ == "__main__":
    print(horses(15))
    print(horses(4))
    print(horses(1))
    print(horses("whoops"))
    print(horses(4.5))

edit: forgot to add code to check for floating-point numbers as input, whoops

Collapse
 
rafaacioly profile image
Rafael Acioly

Nice solution, you could also use the itertools package:

docs.python.org/3/library/itertool...

dev.to/rafaacioly/comment/jkno