def test_perm(self):
''' Permutations. '''
fs_ord = set()
fs_unord = set()
for fs in util.factorize(512, 3):
fs_ord.add(fs)
fs_unord.add(frozenset(fs))
cnt = 0
for fs in fs_unord:
if len(fs) == 3:
# Permutations.
cnt += math.factorial(3)
elif len(fs) == 2:
# Permutations of a, a, b.
cnt += 3
else:
# Pattern a, a, a.
cnt += 1
self.assertEqual(len(fs_ord), cnt)
python类factorial()的实例源码
def combinations(n, r):
return fact(n) / fact(r) / fact(n-r)
def combination(n, k):
""" Code for combination formula i.e. "n choose k" """
from math import factorial
return factorial(n) / (factorial(n - k) * factorial(k))
def __init__(self, margin, beta, beta_min, scale):
self.margin = int(margin)
self.beta = float(beta)
self.beta_min = float(beta_min)
self.scale = float(scale)
self.c_map = []
self.k_map = []
c_m_n = lambda m, n: math.factorial(n) / math.factorial(m) / math.factorial(n-m)
for i in range(margin+1):
self.c_map.append(c_m_n(i, margin))
self.k_map.append(math.cos(i * math.pi / margin))
def estimate_event_probability(self, r, n, p):
# Binomial Event Discriminator
from_timestamp = self.min_timestamp + datetime.timedelta(days=365)
to_timestamp = self.max_timestamp
timestamps, values = self.load_monitor_data(from_timestamp, to_timestamp, None)
values = np.array(values, dtype=float)
prob = math.factorial(n) / (math.factorial(r) * math.factorial(n-r)) * math.pow(p, r) * (math.pow(1-p, n-r))
def fOperator(stack, z, mode):
if mode == 1: # num
stack.append(math.factorial(int(z)))
elif mode == 2: # str
stack.append([''.join(p) for p in itertools.permutations(z)])
elif mode == 3: # list
stack.append([list(p) for p in itertools.permutations(z)])
else:
monadNotImplemented(mode, '')
# g
def KOperator(stack, x, y, mode):
if mode == 1: # num, num
n = int(x)
k = int(y)
if k < 0 or k > n:
stack.append(0)
else:
stack.append(math.factorial(n)/(math.factorial(k)*math.factorial(n-k)))
#elif mode == 2: # num, str
elif mode == 3 or mode == 7: # num, list
n = int(x if mode == 3 else y)
l = y if mode == 3 else x
def subsets(l, n):
if n > len(l) or n < 0:
return []
elif n == len(l):
return [l]
elif n == 0:
return [[]]
elif n == 1:
return [[i] for i in l]
else:
result = []
for i in range(len(l)-n+1):
result += [[l[i]] + s for s in subsets(l[i+1:], n-1)]
return result
stack.append(subsets(l, n))
#elif mode == 4: # str, num
elif mode == 5: # str, str
stack.append(''.join(c for c in x if c in y))
#elif mode == 6: # str, list
#elif mode == 8: # list, str
elif mode == 9: # list, list
stack.append([i for i in x if i in y])
else:
dyadNotImplemented(mode, '')
# ?
def _hypervolume_couboid(self, cuboid):
"""Computes the hypervolume of a single fuzzified cuboid."""
all_dims = [dim for domain in self._core._domains.values() for dim in domain]
n = len(all_dims)
# calculating the factor in front of the sum
weight_product = 1.0
for (dom, dom_weight) in self._weights._domain_weights.items():
for (dim, dim_weight) in self._weights._dimension_weights[dom].items():
weight_product *= dom_weight * sqrt(dim_weight)
factor = self._mu / (self._c**n * weight_product)
# outer sum
outer_sum = 0.0
for i in range(0, n+1):
# inner sum
inner_sum = 0.0
subsets = list(itertools.combinations(all_dims, i))
for subset in subsets:
# first product
first_product = 1.0
for dim in set(all_dims) - set(subset):
dom = filter(lambda (x,y): dim in y, self._core._domains.items())[0][0]
w_dom = self._weights._domain_weights[dom]
w_dim = self._weights._dimension_weights[dom][dim]
b = cuboid._p_max[dim] - cuboid._p_min[dim]
first_product *= w_dom * sqrt(w_dim) * b * self._c
# second product
second_product = 1.0
reduced_domain_structure = self._reduce_domains(self._core._domains, subset)
for (dom, dims) in reduced_domain_structure.items():
n_domain = len(dims)
second_product *= factorial(n_domain) * (pi ** (n_domain/2.0))/(gamma((n_domain/2.0) + 1))
inner_sum += first_product * second_product
outer_sum += inner_sum
return factor * outer_sum
def count_n_choose_k(n, k):
"""Returns the number of k combinations from the set n (n choose k)."""
return (math.factorial(n) /
math.factorial(k) /
math.factorial(n - k))
def binomial_factorial(self,n,k):
"""Calculate binomial coefficient using math.factorial, for testing against binomial
coefficients generated by other means."""
if n >= k:
return int( round( math.factorial(n) / ( math.factorial(k) * math.factorial(n - k) ) ) )
else:
return 0
def test_binomial(self):
"""Test that binomial outputs correct values for, n = 0..nmax, k = 0, n
by comparing against evaluation of math.factorial."""
nmax = 20
for n in range(0,nmax):
for k in range(0,n):
self.assertEqual( binomial(n,k), self.binomial_factorial(n,k) )
def k_comb(n, k):
assert n > k, "Check values in k_comb!"
return int(math.factorial(n) / (math.factorial(k) * math.factorial(n - k)))
def test_scheme(scheme, tol):
degree = check_degree(
lambda poly: quadpy.e1r.integrate(poly, scheme),
lambda k: math.factorial(k[0]),
1,
scheme.degree + 1,
tol=tol
)
assert degree == scheme.degree, \
'Observed: {} expected: {}'.format(degree, scheme.degree)
return
def integrate_monomial_over_enr(k):
if numpy.any(k % 2 == 1):
return 0
n = len(k)
return 2 * math.factorial(sum(k) + n - 1) * numpy.prod([
math.gamma((kk+1) / 2.0) for kk in k
]) / math.gamma((sum(k) + n) / 2)
def plot(scheme, show_axes=True):
ax = plt.gca()
plt.axis('equal')
if not show_axes:
ax.set_axis_off()
n = 2
I0 = 2*math.factorial(n-1)*math.pi**(0.5*n) / math.gamma(0.5*n)
helpers.plot_disks(
plt, scheme.points, scheme.weights, I0
)
return
def _size_cond(self, size):
n = int(size)
# r = 2
# f = math.factorial
# return int(f(n) / f(r) / f(n - r))
return int((n * (n - 1)) / 2)
def size_cond(size):
n = size
r = 2
f = math.factorial
return int(f(n) / f(r) / f(n-r))
def nCr(n,r):
f = math.factorial
return f(n) / f(r) / f(n-r)
def facSum(n):
sn = str(n)
sumfac = 0
for val in sn:
valInt = int(val)
sumfac += factorial(valInt)
return sumfac
def sumOfDigFac(n):
stringn = str(n)
sumoffac = 0
for i in xrange(0, len(stringn)):
sumoffac += math.factorial(int(stringn[i]))
if sumoffac != n:
return False
return True