can you write a python code for a function of combination and permutation
Certainly! Here's a Python code that includes functions for combination and permutation calculations:
import math
def combination(n, r):
"""
Calculates the combination of n choose r.
"""
return math.factorial(n) // (math.factorial(r) * math.factorial(n - r))
def permutation(n, r):
"""
Calculates the permutation of n choose r.
"""
return math.factorial(n) // math.factorial(n - r)
# Example usage
n = 5
r = 3
# Calculate combination
comb = combination(n, r)
print(f"Combination of {n} choose {r} = {comb}")
# Calculate permutation
perm = permutation(n, r)
print(f"Permutation of {n} choose {r} = {perm}")
In this code, the combination function calculates the combination of n choose r using the formula n! / (r! * (n-r)!), where n! represents the factorial of n. The permutation function calculates the permutation of n choose r using the formula n! / (n-r)!. The code then demonstrates the usage of these functions by calculating the combination and permutation for n=5 and r=3.
原文地址: http://www.cveoy.top/t/topic/i1Dm 著作权归作者所有。请勿转载和采集!