How to compute nPr in sagemath
How to compute nPr in sagemath? Please help
How to compute nPr in sagemath? Please help
The following method avoids computing factorials explicitly, which can be computationally expensive for large values of n and r. Instead, it computes the product of a sequence of values using a generator expression, which is more memory-efficient and faster than computing factorials. You can compute perm(n, r) using a prod
function, which is a built-in SageMath function that computes the product of a sequence of values.
See the code:
perm(n, r) = prod(n - i for i in range(r))
Hello! I am assuming nPr means "n permutation r". Unfortunately, SageMath doesn't have a command for that purpose. However, if you remember that
$$nPr = \frac{n!}{(n-r)!} = \binom{n}{r}r!,$$
you can make something like this:
perm(n, r) = factorial(n) / factorial(n - r)
or even:
perm(n, r) = binomial(n, r) * factorial(r)
Hope this helps!
To my surprise, the former is about 12 times faster than the latter :
sage: %timeit Permutations(5,3).cardinality()
2.31 µs ± 450 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)
sage: sage: %timeit binomial(5,3)*factorial(3)
27.3 µs ± 860 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
Go figure...
Please start posting anonymously - your entry will be published after you log in or create a new account.
Asked: 2023-07-15 13:42:28 +0100
Seen: 355 times
Last updated: Jul 21 '23
What is nPr?