Python math.factorial() Examples

The following are 30 code examples of math.factorial(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module math , or try the search function .
Example #1
Source File: test_math.py    From ironpython2 with Apache License 2.0 7 votes vote down vote up
def test_math_subclass(self):
        """verify subtypes of float/long work w/ math functions"""
        import math
        class myfloat(float): pass
        class mylong(long): pass

        mf = myfloat(1)
        ml = mylong(1)

        for x in math.log, math.log10, math.log1p, math.asinh, math.acosh, math.atanh, math.factorial, math.trunc, math.isinf:
            try:
                resf = x(mf)
            except ValueError:
                resf = None
            try:
                resl = x(ml)
            except ValueError:
                resl = None
            self.assertEqual(resf, resl) 
Example #2
Source File: test_trajGen3D.py    From quadcopter-simulation with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_get_poly_cc_k(self):
        cc = trajGen3D.get_poly_cc(4, 1, 1)
        expected = [0, 1, 2, 3]
        np.testing.assert_array_equal(cc, expected)

        cc = trajGen3D.get_poly_cc(4, 2, 2)
        expected = [0, 0, 2, 12]
        np.testing.assert_array_equal(cc, expected)

        cc = trajGen3D.get_poly_cc(8, 7, 1)
        expected = [0, 0, 0, 0, 0, 0, 0, math.factorial(7)]
        np.testing.assert_array_equal(cc, expected)

        cc = trajGen3D.get_poly_cc(8, 8, 1)
        expected = np.zeros(8)
        np.testing.assert_array_equal(cc, expected) 
Example #3
Source File: sol2.py    From Python with MIT License 6 votes vote down vote up
def solution(n):
    """Returns the sum of the digits in the number 100!
    >>> solution(100)
    648
    >>> solution(50)
    216
    >>> solution(10)
    27
    >>> solution(5)
    3
    >>> solution(3)
    6
    >>> solution(2)
    2
    >>> solution(1)
    1
    """
    return sum([int(x) for x in str(factorial(n))]) 
Example #4
Source File: test_util.py    From nn_dataflow with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) 
Example #5
Source File: sol3.py    From Python with MIT License 6 votes vote down vote up
def solution(n):
    """Returns the sum of the digits in the number 100!
    >>> solution(1000)
    10539
    >>> solution(200)
    1404
    >>> solution(100)
    648
    >>> solution(50)
    216
    >>> solution(10)
    27
    >>> solution(5)
    3
    >>> solution(3)
    6
    >>> solution(2)
    2
    >>> solution(1)
    1
    >>> solution(0)
    1
    """
    return sum(map(int, str(factorial(n)))) 
Example #6
Source File: macros.py    From pyth with MIT License 6 votes vote down vote up
def combinations(a, b):
    if isinstance(a, int) and isinstance(b, int):
        # compute n C r
        n, r = a, min(b, a - b)
        if r == 0:
            return 1
        if r < 0:
            r = max(b, a - b)
            if r < 0:
                return 0

        num = functools.reduce(operator.mul, range(n, n - r, -1), 1)
        den = math.factorial(r)

        return num // den

    if is_col(a) and isinstance(b, int):
        return itertools_norm(itertools.combinations, a, b)

    return unknown_types(combinations, ".c", a, b) 
Example #7
Source File: pure_math.py    From ufora with Apache License 2.0 6 votes vote down vote up
def __call__(self, val):
        if not math.floor(val) == val:
            raise ValueError(
                "factorial() only accepts integral values"
                )

        if val < 0:
            raise ValueError(
                "factorial() not defined for negative values"
                )

        ix = 1
        res = 1
        while ix <= val:
            res = res * ix
            ix = ix + 1

        return res 
Example #8
Source File: wave.py    From ocelot with GNU General Public License v3.0 6 votes vote down vote up
def calc_phase_delay(coeff, w, w0):
    """
    expression for the phase -- coeff[0] + coeff[1]*(w - w0)/1! + coeff[2]*(w - w0)**2/2! + coeff[3]*(w - w0)**3/3!
    coeff is a list with
    coeff[0] =: measured in [rad]      --- phase
    coeff[1] =: measured in [fm s ^ 1] --- group delay
    coeff[2] =: measured in [fm s ^ 2] --- group delay dispersion (GDD)
    coeff[3] =: measured in [fm s ^ 3] --- third-order dispersion (TOD)
    ...
    """
    delta_w = w - w0
    _logger.debug('calculating phase delay')
    _logger.debug(ind_str + 'coeffs for compression = {}'.format(coeff))
    coeff_norm = [ci / (1e15) ** i / factorial(i) for i, ci in enumerate(coeff)]
    coeff_norm = list(coeff_norm)[::-1]
    _logger.debug(ind_str + 'coeffs_norm = {}'.format(coeff_norm))
    delta_phi = np.polyval(coeff_norm, delta_w)
    _logger.debug(ind_str + 'delta_phi[0] = {}'.format(delta_phi[0]))
    _logger.debug(ind_str + 'delta_phi[-1] = {}'.format(delta_phi[-1]))
    _logger.debug(ind_str + 'done')

    return delta_phi 
Example #9
Source File: collection_utils.py    From QCPortal with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def nCr(n: int, r: int) -> int:
    """
    Compute the binomial coefficient n! / (k! * (n-k)!)

    Parameters
    ----------
    n : int
        Number of samples
    r : int
        Denominator

    Returns
    -------
    ret : int
        Value
    """
    return math.factorial(n) / math.factorial(r) / math.factorial(n - r) 
Example #10
Source File: linalg.py    From NURBS-Python with MIT License 6 votes vote down vote up
def binomial_coefficient(k, i):
    """ Computes the binomial coefficient (denoted by *k choose i*).

    Please see the following website for details: http://mathworld.wolfram.com/BinomialCoefficient.html

    :param k: size of the set of distinct elements
    :type k: int
    :param i: size of the subsets
    :type i: int
    :return: combination of *k* and *i*
    :rtype: float
    """
    # Special case
    if i > k:
        return float(0)
    # Compute binomial coefficient
    k_fact = math.factorial(k)
    i_fact = math.factorial(i)
    k_i_fact = math.factorial(k - i)
    return float(k_fact / (k_i_fact * i_fact)) 
Example #11
Source File: manabase.py    From Manabase with GNU General Public License v2.0 6 votes vote down vote up
def comb(n, k):
	"""Simple combinations function, the number of ways to choose
	k objects from n given objects.

	>>> print(comb(7, 3))
	35
	>>> print(comb(7, 0))
	1
	"""
	if is_int(n) and is_int(k):
		if k >= 0 and k <= n:
			return int(math.factorial(n) / (math.factorial(k) * math.factorial(n-k)))
		else:
			return 0
	else:
		raise ValueError('Can\'t take factorials of non-integers; you passed %n and %k to comb().' % (n, k)) 
Example #12
Source File: calculator.py    From Jarvis with MIT License 6 votes vote down vote up
def fact(self):
        try:
            self.a = self.num.get()
            self.buffer["text"] = str(self.a) + "!"
            if float(self.a) >= 0:
                self.an = str(math.factorial(float(self.a)))
                self.ans["text"] = self.an
                if len(self.an) > 17:
                    self.ans["text"] = "Out of Range"
            else:
                self.ans["text"] = "Error"
        except ValueError:
            self.ans["text"] = "Invalid Input "
        except TypeError:
            self.ans["text"] = "Invalid Input "
        except OverflowError:
            self.ans["text"] = "Out of range" 
Example #13
Source File: core.py    From Deep-Learning-with-TensorFlow-Second-Edition with MIT License 6 votes vote down vote up
def init_main_block(self):
        self.x_pow_cache = {}
        self.matmul_cache = {}
        self.outputs = self.b
        with tf.name_scope('linear_part') as scope:
            contribution = utils.matmul_wrapper(self.train_x, self.w[0], self.input_type)
        self.outputs += contribution
        for i in range(2, self.order + 1):
            with tf.name_scope('order_{}'.format(i)) as scope:
                raw_dot = utils.matmul_wrapper(self.train_x, self.w[i - 1], self.input_type)
                dot = tf.pow(raw_dot, i)
                if self.use_diag:
                    contribution = tf.reshape(tf.reduce_sum(dot, [1]), [-1, 1])
                    contribution /= 2.0**(i-1)
                else:
                    initialization_shape = tf.shape(dot)
                    for in_pows, out_pows, coef in utils.powers_and_coefs(i):
                        product_of_pows = tf.ones(initialization_shape)
                        for pow_idx in range(len(in_pows)):
                            pmm = self.pow_matmul(i, in_pows[pow_idx])
                            product_of_pows *= tf.pow(pmm, out_pows[pow_idx])
                        dot -= coef * product_of_pows
                    contribution = tf.reshape(tf.reduce_sum(dot, [1]), [-1, 1])
                    contribution /= float(math.factorial(i))
            self.outputs += contribution 
Example #14
Source File: numpy_helper.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def expm(a):
    '''Equivalent to scipy.linalg.expm'''
    bs = [a.copy()]
    n = 0
    for n in range(1, 14):
        bs.append(ddot(bs[-1], a))
        radius = (2**(n*(n+2))*math.factorial(n+2)*1e-16) **((n+1.)/(n+2))
        #print(n, radius, bs[-1].max(), -bs[-1].min())
        if bs[-1].max() < radius and -bs[-1].min() < radius:
            break

    y = numpy.eye(a.shape[0])
    fac = 1
    for i, b in enumerate(bs):
        fac *= i + 1
        b *= (.5**(n*(i+1)) / fac)
        y += b
    buf, bs = bs[0], None
    for i in range(n):
        ddot(y, y, 1, buf, 0)
        y, buf = buf, y
    return y 
Example #15
Source File: test_bipartite.py    From matchpy with MIT License 5 votes vote down vote up
def test_completeness(n, m):
    graph = BipartiteGraph(map(lambda x: (x, True), itertools.product(range(n), range(m))))
    count = sum(1 for _ in enum_maximum_matchings_iter(graph))
    expected_count = m > 0 and math.factorial(n) / math.factorial(n - m) or 0
    assert count == expected_count 
Example #16
Source File: _ncr.py    From abydos with GNU General Public License v3.0 5 votes vote down vote up
def _ncr(n: float, r: float) -> float:
    r"""Return n Choose r.

    Cf. https://en.wikipedia.org/wiki/Combination

    Parameters
    ----------
    n : float
        The number of elements in the set/multiset
    r : float
        The number of elements to choose

    Returns
    -------
    int or float
        n Choose r

    Examples
    --------
    >>> _ncr(4, 2)
    6
    >>> _ncr(10, 3)
    120

    .. versionadded:: 0.4.0

    """
    if isinstance(r, int) and isinstance(n, int):
        if not r:
            return 1
        if r > n:
            return 0
        return int(factorial(n) / (factorial(r) * factorial(n - r)))
    return gamma(n + 1) / (gamma(r + 1) * gamma(n - r + 1)) 
Example #17
Source File: encode_lib_common.py    From atac-seq-pipeline with MIT License 5 votes vote down vote up
def nCr(n, r):  # combination
    return math.factorial(n)/math.factorial(r)/math.factorial(n-r) 
Example #18
Source File: MathTestCases.py    From ufora with Apache License 2.0 5 votes vote down vote up
def test_pure_python_math_module(self):
        vals = [1, -.5, 1.5, 0, 0.0, -2, -2.2, .2]

        # not being tested: math.asinh, math.atanh, math.lgamma, math.erfc, math.acos
        def f():
            functions = [
                math.sqrt, math.cos, math.sin, math.tan, math.asin, math.atan,
                math.acosh, math.cosh, math.sinh, math.tanh, math.ceil,
                math.erf, math.exp, math.expm1, math.factorial, math.floor,
                math.log, math.log10, math.log1p
            ]
            tr = []
            for idx1 in range(len(vals)):
                v1 = vals[idx1]
                for funIdx in range(len(functions)):
                    function = functions[funIdx]
                    try:
                        tr = tr + [function(v1)]
                    except ValueError as ex:
                        pass

            return tr

        r1 = self.evaluateWithExecutor(f)
        r2 = f()
        self.assertGreater(len(r1), 100)
        self.assertTrue(numpy.allclose(r1, r2, 1e-6)) 
Example #19
Source File: core.py    From AeroPy with MIT License 5 votes vote down vote up
def K(r, n):
    K = math.factorial(n)/(math.factorial(r)*math.factorial(n-r))
    return K

# Upper surface differential 
Example #20
Source File: distinct_initial_matrices.py    From InterviewBit with MIT License 5 votes vote down vote up
def _permWithRepetition(self, arr):
        n, tmp, div = len(arr), 1, 1
        for i in range(1, n):
            if arr[i - 1] == arr[i]:
                tmp += 1
            else:
                tmp = 1
                div *= math.factorial(tmp)
        return math.factorial(n) // div

    # @param A : list of integers
    # @return an integer 
Example #21
Source File: bezier.py    From svgpathtools with MIT License 5 votes vote down vote up
def bezier2polynomial(p, numpy_ordering=True, return_poly1d=False):
    """Converts a tuple of Bezier control points to a tuple of coefficients
    of the expanded polynomial.
    return_poly1d : returns a numpy.poly1d object.  This makes computations
    of derivatives/anti-derivatives and many other operations quite quick.
    numpy_ordering : By default (to accommodate numpy) the coefficients will
    be output in reverse standard order."""
    if len(p) == 4:
        coeffs = (-p[0] + 3*(p[1] - p[2]) + p[3],
                  3*(p[0] - 2*p[1] + p[2]),
                  3*(p[1]-p[0]),
                  p[0])
    elif len(p) == 3:
        coeffs = (p[0] - 2*p[1] + p[2],
                  2*(p[1] - p[0]),
                  p[0])
    elif len(p) == 2:
        coeffs = (p[1]-p[0],
                  p[0])
    elif len(p) == 1:
        coeffs = p
    else:
        # https://en.wikipedia.org/wiki/Bezier_curve#Polynomial_form
        n = len(p) - 1
        coeffs = [fac(n)//fac(n-j) * sum(
            (-1)**(i+j) * p[i] / (fac(i) * fac(j-i)) for i in range(j+1))
            for j in range(n+1)]
        coeffs.reverse()
    if not numpy_ordering:
        coeffs = coeffs[::-1]  # can't use .reverse() as might be tuple
    if return_poly1d:
        return poly1d(coeffs)
    return coeffs 
Example #22
Source File: utils.py    From Deep-Learning-with-TensorFlow-Second-Edition with MIT License 5 votes vote down vote up
def initial_coefficient(decomposition):
    """Compute initial coefficient of the decomposition."""
    order = np.sum(decomposition)
    coef = math.factorial(order)
    coef /= np.prod([math.factorial(x) for x in decomposition])
    _, counts = np.unique(decomposition, return_counts=True)
    coef /= np.prod([math.factorial(c) for c in counts])
    return coef 
Example #23
Source File: bezier.py    From svgpathtools with MIT License 5 votes vote down vote up
def n_choose_k(n, k):
    return fac(n)//fac(k)//fac(n-k) 
Example #24
Source File: __init__.py    From py-expression-eval with MIT License 5 votes vote down vote up
def fac(self, a):  # a!
        return math.factorial(a) 
Example #25
Source File: preprocessing_funcs.py    From NLP_Toolkit with Apache License 2.0 5 votes vote down vote up
def nCr(n,r):
    f = math.factorial
    return int(f(n)/(f(r)*f(n-r)))

### remove stopwords and non-words from tokens list 
Example #26
Source File: lingam.py    From monasca-analytics with Apache License 2.0 5 votes vote down vote up
def _perms(n):
        k = 1
        p = np.empty((2 * n - 1, math.factorial(n)), np.uint8)
        for i in range(n):
            p[i, :k] = i
            p[i + 1:2 * i + 1, :k] = p[:i, :k]
            for j in range(i):
                p[:i + 1, k * (j + 1):k * (j + 2)] = p[j + 1:j + i + 2, :k]
            k *= i + 1
        return p[:n, :] 
Example #27
Source File: coefs.py    From findiff with MIT License 5 votes vote down vote up
def _build_rhs(p, q, deriv):
    """The right hand side of the equation system matrix"""

    b = [0 for _ in range(p+q+1)]
    b[deriv] = math.factorial(deriv)
    return np.array(b) 
Example #28
Source File: 60_permutation-sequence.py    From algorithm with Apache License 2.0 5 votes vote down vote up
def getPermutation(self, n: int, k: int) -> str:
        nums = [str(i) for i in range(1, n + 1)]
        output_str = ""
        n -= 1
        while n > -1:
            number_combination = math.factorial(n)  # 每组组合数总和
            output_number_index = (
                math.ceil(k / number_combination) - 1
            )  # 不用\\的原因是因为 1 1希望输出的是0,"\\"会输出1
            output_str += nums[output_number_index]
            nums.pop(output_number_index)
            k %= number_combination
            n -= 1
        return output_str 
Example #29
Source File: test_math.py    From oss-ftp with MIT License 5 votes vote down vote up
def testFactorial(self):
        def fact(n):
            result = 1
            for i in range(1, int(n)+1):
                result *= i
            return result
        values = range(10) + [50, 100, 500]
        random.shuffle(values)
        for x in values:
            for cast in (int, long, float):
                self.assertEqual(math.factorial(cast(x)), fact(x), (x, fact(x), math.factorial(x)))
        self.assertRaises(ValueError, math.factorial, -1)
        self.assertRaises(ValueError, math.factorial, math.pi) 
Example #30
Source File: test_math.py    From BinderFilter with MIT License 5 votes vote down vote up
def testFactorial(self):
        def fact(n):
            result = 1
            for i in range(1, int(n)+1):
                result *= i
            return result
        values = range(10) + [50, 100, 500]
        random.shuffle(values)
        for x in values:
            for cast in (int, long, float):
                self.assertEqual(math.factorial(cast(x)), fact(x), (x, fact(x), math.factorial(x)))
        self.assertRaises(ValueError, math.factorial, -1)
        self.assertRaises(ValueError, math.factorial, math.pi)