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
importmathdefnchoosek(n,k):n_fac=math.factorial(n)denominator=math.factorial(k)*math.factorial(n-k)returnn_fac/denominatordefhorses(num_horses):try:# check for non-integer but still numerical input
ifint(num_horses)!=num_horses:returnNoneexceptValueError:# check for non-numerical input
returnNoneifnum_horses<=3:returnnum_horsesreturnint(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
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
choosek
/binomial coefficient for the horses, wheren
is the total number of horses, andk
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 ton!
, we can multiply the result of ourn
choosek
by 6 (which is just a shorthand for multiplying by3!
, as3! = 6
). Putting that all together with a little bit of error checking, we have the following short Python solution:edit: forgot to add code to check for floating-point numbers as input, whoops
Nice solution, you could also use the
itertools
package:dev.to/rafaacioly/comment/jkno