Ejemplo n.º 1
0
def comb_mod(n, r, mod):
    """Returns comb(n, r) % mod using Lucas theorem. mod has to be prime."""
    c = 1
    while r > 0:
        r, rm = divmod(r, mod)
        n, nm = divmod(n, mod)
        c *= comb(nm, rm)
        c %= mod
    return c
Ejemplo n.º 2
0
Archivo: misc.py Proyecto: ricma/quadpy
def comb(a, b):
    if sys.version < "3.8":
        try:
            binom = math.factorial(a) // math.factorial(b) // math.factorial(
                a - b)
        except ValueError:
            binom = 0
        return binom
    return math.comb(a, b)
Ejemplo n.º 3
0
 def __weight(self, distribution):
     n_array = numpy.array(distribution)
     unique, counts = numpy.unique(n_array, return_counts=True)
     total = 0
     cardinal = 1
     for item in counts:
         cardinal = cardinal * math.comb(5 - total, item)
         total += item
     return cardinal
Ejemplo n.º 4
0
def stern_iteration_cost(p, l, w, n, k):

    li = comb(k//2, p)
    #num = 2*li + (li**2) * pow(2, -l) 
    num = (li**2) * pow(2, -l) 

    if num == 0.0: return 0

    return log(num, 2)
Ejemplo n.º 5
0
def main():
    n = int(input())

    d = defaultdict(int)
    for _ in range(n):
        s = input()
        if s[0] in 'MARCH':
            d[s[0]] += 1

    a = comb(sum(d.values()), 3)
    b = 0
    for i in d.keys():
        if d[i] >= 2:
            b += comb(d[i], 2) * (sum(d.values()) - d[i])
        if d[i] >= 3:
            b += comb(d[i], 3)

    print(a - b)
Ejemplo n.º 6
0
 def to_vector(self):
     # Empty vector
     res = [0] * sum(
         [comb(self.variable_num, i) for i in range(self.degree + 1)])
     # Place a 1 for each monomial in the right place.
     active_index = [i.monomial_to_index(self.variable_num) for i in self]
     for monomial in self:
         res[monomial.monomial_to_index(self.variable_num)] = 1
     return res
Ejemplo n.º 7
0
def prob(n, p, r):
    '''
        p là xác suất có được mặt ngửa của 1 đồng xu
        r là số lần tung đồng xu được mặt ngửa
        n+r là số lần tung đồng xu để có r mặt ngửa
        n là số lần tung đồng xu được mặt sấp
        
    '''
    return math.comb(n + r - 1, n) * ((1 - p)**n) * (p**r)
Ejemplo n.º 8
0
 def test_n_choose_k(self):
     n, k = 4, 3
     for n, k in [(4, 3), (6, 3), (7, 6), (10, 6)]:
         expected = comb(n, k)
         produced = BinomialCoefficients.n_choose_k(n, k)
         print(
             f" n = {n}, k = {k}, Produced: {produced}, Expected: {expected}"
         )
         self.assertEqual(expected, produced)
Ejemplo n.º 9
0
    def climbStairs(self, n: int) -> int:
        step1_cnt, sum_comb = n % 2, 0

        for step2_cnt in range(n // 2, -1, -1):
            step2_comb = comb(step2_cnt + step1_cnt, step2_cnt)
            sum_comb = sum_comb + step2_comb
            step1_cnt += 2

        return sum_comb
Ejemplo n.º 10
0
    def uniquePaths4(self, m: int, n: int) -> int:
        '''
        Combination Math  组合数学计算公式
        https://leetcode-cn.com/problems/unique-paths/solution/bu-tong-lu-jing-by-leetcode-solution-hzjf/

        我看不懂,但我大为震撼 =-=
        '''
        import math
        return math.comb(m + n - 2, n - 1)
Ejemplo n.º 11
0
def take_training(courses):
    topic_count, difficulty_count = defaultdict(int), defaultdict(int)
    for topic, difficulty in courses:
        topic_count[topic] += 1
        difficulty_count[difficulty] += 1

    bad = sum((difficulty_count[difficulty] - 1) * (topic_count[topic] - 1)
              for topic, difficulty in courses)
    return comb(len(courses), 3) - bad
Ejemplo n.º 12
0
 def uniquePaths(self, m, n):
     """
     :type m: int
     :type n: int
     :rtype: int
     """
     if m <= 1 or n <= 1:
         return 1
     return comb(m + n - 2, min(m - 1, n - 1))
Ejemplo n.º 13
0
def D(N):
    count = 0
    for n in range(1, N + 1):
        # Required number of equal digits
        # for the number to be dominating
        required = n // 2 + 1
        rest = n - required
        count += sum([comb(n, r) * 9**(r + 1) for r in range(rest + 1)])
    return count
Ejemplo n.º 14
0
def main():
    """
    長さ L の棒の分割後の各棒の長さが全て正整数になるためには,整数長さ以外の場所を切ってはいけない.
    切る位置の候補は L-1 個あり,そこから異なる 11 箇所を選ぶ場合の数を求めれば良い.
    これは comb(L-1, 11) で求められる.
    """
    l_input = int(input())
    ans = comb(l_input-1, 11)
    return ans
Ejemplo n.º 15
0
def ss_val(ss):
    aux = 1
    cols = [5, 5, 5, 5, 5]
    for row in ss:
        # print(row)
        for i, v in enumerate(row):
            aux *= comb(cols[i], v)
            cols[i] -= v
    return aux
Ejemplo n.º 16
0
    def atMostNGivenDigitSet(self, digits, n: int) -> int:
        digits_in_N = len(str(n))
        numbers = len(digits)
        sum = [(comb(numbers, 1)) ** i for i in range(1, digits_in_N - 1)]


        for place,num in enumerate(str(n)):
            pos = self.binary_search(digits, num)
            if pos == -1:
Ejemplo n.º 17
0
def degelev(poly, degs):
    # Degree elevation of Bernstein-form polynomials.
    # See also Tsai and Farouki 2001.
    n = len(poly) - 1
    ret = []
    nchoose = [math.comb(n, j) for j in range(n // 2 + 1)]
    degschoose = (nchoose if degs == n else
                  [math.comb(degs, j) for j in range(degs // 2 + 1)])
    for k in range(0, n + degs + 1):
        ndk = math.comb(n + degs, k)
        c = 0
        for j in range(max(0, k - degs), min(n, k) + 1):
            degs_choose_kj = (degschoose[k - j] if k - j < len(degschoose) else
                              degschoose[degs - (k - j)])
            n_choose_j = nchoose[j] if j < len(nchoose) else nchoose[n - j]
            c += poly[j] * degs_choose_kj * n_choose_j / ndk
        ret.append(c)
    return ret
Ejemplo n.º 18
0
 def dfs(choices, cur_n):
     if cur_n == 0:
         return 1
     if choices <= 0:
         return 0
     res = 0
     for i in range(0, min(cur_n, k) + 1):
         res += int(comb(cur_n, i)) * dfs(choices - 1, cur_n - i) % MOD
     return res % MOD
Ejemplo n.º 19
0
 def count(index, delta, ca):
     if index == n: return 1 if delta == 0 and ca == s2 else 0
     total = sum([
         count(index + 1, delta, ca + x) * comb(balls[index], x)
         for x in range(1, balls[index])
     ])
     total += count(index + 1, delta + 1, ca)
     total += count(index + 1, delta - 1, ca + balls[index])
     return total
 def dfs(cur):
     if not g[cur]:
         return 1, 1
     ans, l = 1, 0
     for nxt in g[cur]:
         tmp, r = dfs(nxt)
         ans = (ans * tmp * math.comb(l+r, r)) % MOD
         l += r
     return ans, l + 1
Ejemplo n.º 21
0
 def helper(arr):
     if len(arr) < 3:
         return 1
     val = arr[0]
     left = [arr[i] for i in range(1,len(arr)) if arr[i]<val]
     right = [arr[i] for i in range(1,len(arr)) if arr[i]>val]
     # we can use the length of left arr or right arr - same thing !
     combinations = math.comb((len(left)+len(right)),len(left))
     return combinations * helper(left) * helper(right)
Ejemplo n.º 22
0
 def comb(n, k):
     if k > n:
         return 0
     if k > n // 2:
         return comb(n, n - k)
     C = 1
     for i in range(k):
         C = (C * (n - i)) // (i + 1)
     return C
Ejemplo n.º 23
0
        def rec(ns):
            if len(ns) <= 2: return 1
            left, right = [], []
            for n in ns[1:]:
                if n < ns[0]: left.append(n)
                else: right.append(n)

            return math.comb(len(left) + len(right),
                             len(left)) * rec(left) * rec(right) % MOD
Ejemplo n.º 24
0
def main(H, flag, problem, m, max_evaluations):
    uploadBenchmark(problem)
    n, m, lb, ub = parameters(problem, m)
    pc = 1  #Crossover probability
    nc = 20  #Crossover distribution index
    pm = 1 / n  #Mutation probability
    nm = 20  #Mutation distribution index
    N = math.comb(H + m - 1, m - 1)
    P = randomPopulation(N, n, m, lb, ub, problem)
    W = uniformReferencePoints(N, m)
    zmin = np.min(P.obj, axis=0)
    zmax = np.max(P.obj, axis=0)
    zmax[zmax - zmin <= 1e-6] = 1
    if (flag == 2):
        Wprime = np.random.rand(N, m)
    if (flag == 3):
        A, Wprime = RefPointAdaption(P.obj, W, zmin, zmax)
    evaluations = 0
    while (evaluations < max_evaluations):
        Q = generateOffspring(P, lb, ub, pc, nc, pm, nm, problem)
        R = population(np.concatenate((P.dec, Q.dec), axis=0),
                       np.concatenate((P.obj, Q.obj), axis=0))
        if (flag == 0):
            P = environmentalSelection(R, W, N, zmin, zmax, flag)
        if (flag == 1):
            P = environmentalSelection(R, W, N, zmin, zmax, flag)
            W = adaptive(P.obj, W, N)
        if (flag == 2):
            P = environmentalSelection(R, np.concatenate((W, Wprime), axis=0),
                                       N, zmin, zmax, flag)
            Wprime = referenceVectorRegeneration(P.obj, Wprime)
        if (flag == 3):
            A, Wprime = RefPointAdaption(np.concatenate((A, Q.obj), axis=0), W,
                                         zmin, zmax)
            P = environmentalSelection(R, Wprime, N, zmin, zmax, flag)
        zmin = np.min(np.concatenate(([zmin], P.obj), axis=0), axis=0)
        zmax = np.max(P.obj, axis=0)
        zmax[zmax - zmin <= 1e-6] = 1
        evaluations += N
        if (flag == 0):
            print('Algorithm: IGD+-MaOEA-RS, '
                  f'Problem: {problem}, '
                  f'Evaluations: {evaluations}')
        if (flag == 1):
            print('Algorithm: A-IGD+-MaOEA-RS, '
                  f'Problem: {problem}, '
                  f'Evaluations: {evaluations}')
        if (flag == 2):
            print('Algorithm: R-IGD+-MaOEA-RS, '
                  f'Problem: {problem}, '
                  f'Evaluations: {evaluations}')
        if (flag == 3):
            print('Algorithm: AR-IGD+-MaOEA-RS, '
                  f'Problem: {problem}, '
                  f'Evaluations: {evaluations}')
    return P
Ejemplo n.º 25
0
def info_func(n, left, N, alpha=0.05):
    d = {}
    d['alpha'] = alpha
    d['n'] = n
    d['N'] = N
    d['left'] = left
    d['or_arr'] = np.random.randint(d['left'], d['N'] + 1, d['n'])
    d['array'] = sorted(d['or_arr'])

    table = collections.OrderedDict(collections.Counter(d['array']))
    d['xi'] = list(table.keys())
    d['mi'] = list(table.values())
    table.clear()

    sum = 0
    for i in range(len(d['xi'])):
        sum += d['xi'][i] * d['mi'][i]

    d['p*'] = round(sum / (d['N'] * d['n']), 4)
    d['q*'] = 1 - d['p*']

    d['pi'] = []
    d['n*pi'] = []
    for i in range(d['N'] + 1):
        pi = math.comb(d['N'], i) * d['p*']**i * d['q*']**(d['N'] - i)
        d['pi'].append(round(pi, 4))
        d['n*pi'].append(round(pi * d['n'], 4))

    print('xi', " ", 'mi', " ", 'pi', " ", 'n*pi')
    for i in range(d['N'] + 1):
        print(d['xi'][i], " ", d['mi'][i], " ", d['pi'][i], " ", d['n*pi'][i])

    d['xi_copy'] = copy.deepcopy(d['xi'])
    d['mi_copy'] = copy.deepcopy(d['mi'])
    d['pi_copy'] = copy.deepcopy(d['pi'])
    d['n*pi_copy'] = copy.deepcopy(d['n*pi'])

    merge(d)

    d['d.f.'] = len(d['xi']) - 2
    d['pi'] = [round(i, 4) for i in d['pi']]
    d['n*pi'] = [round(i, 4) for i in d['n*pi']]

    d['x^2emp'] = 0
    for i in range(len(d['n*pi'])):
        d['x^2emp'] += (d['mi'][i] - d['n*pi'][i])**2 / d['n*pi'][i]
    d['x^2emp'] = round(d['x^2emp'], 5)
    for i in range(len(d['n*pi'])):
        print(d['xi'][i], " ", d['mi'][i], " ", d['pi'][i], " ", d['n*pi'][i])

    d['x^2kr'] = round(stats.chi2.isf(d['alpha'], d['d.f.']), 5)
    print(d['x^2emp'])
    print(len(d['xi']))
    print(d['d.f.'])
    print(d['x^2kr'])
    return d
Ejemplo n.º 26
0
    def onClick(self, tile):
        totaltiles = len(
            self.getNeighbors(tile["coords"]["x"], tile["coords"]["y"]))
        possible = 0
        totalmines = tile["mines"]
        if self.startTime == None:
            self.startTime = datetime.now()

        if tile["isMine"] == True:
            # end game
            self.gameOver(False)
            return

        self.makeGreen(tile["coords"]["x"], tile["coords"]["y"])
        numrevealed = 0
        unclicked = 0
        # calculating unclicked neighbors and number of mines revealed
        if tile["mines"] > 0:
            for k in self.getNeighbors(tile["coords"]["x"],
                                       tile["coords"]["y"]):
                if k["state"] == 0 and k["isMine"] == True:
                    numrevealed += 1
                    if k["state"] == STATE_FLAGGED:
                        numrevealed -= 1
                if k["state"] == 0:
                    unclicked += 1
                if k["state"] == 1:
                    totalmines += k["mines"]
            tile["heuristic"] = math.comb(unclicked, numrevealed)
        possible = tile["heuristic"]
        # print('this is total mines', totalmines)
        # print('this is possible', possible)
        # checking if theres a possibility of a mine
        if possible == 1:
            for k in self.getNeighbors(tile["coords"]["x"],
                                       tile["coords"]["y"]):
                if k["state"] == 0 and k[
                        "isMine"] == True:  #Only mines are flagged
                    k["button"].config(image=self.images["flag"])
                    self.flagCount += 1
                    k["state"] = STATE_FLAGGED

        if tile["mines"] == 0:
            tile["button"].config(image=self.images["clicked"])
            self.clearSurroundingTiles(tile["id"])
        else:
            tile["button"].config(image=self.images["numbers"][tile["mines"] -
                                                               1])
        if tile["state"] != STATE_CLICKED:
            tile["state"] = STATE_CLICKED
            self.clickedCount += 1
        if self.clickedCount == (SIZE_X * SIZE_Y) - self.mines:
            self.gameOver(True)

        self.updateTile(tile["coords"]["x"], tile["coords"]["y"])
        self.updateUnclicked()  #updates the unclicked list
def vandermonde_matrix(cell, degree, points, grad=False):
    """Construct the generalised Vandermonde matrix for polynomials of the
    specified degree on the cell provided.

    :param cell: the :class:`~.reference_elements.ReferenceCell`
    :param degree: the degree of polynomials for which to construct the matrix.
    :param points: a list of coordinate tuples corresponding to the points.
    :param grad: whether to evaluate the Vandermonde matrix or its gradient.

    :returns: the generalised :ref:`Vandermonde matrix <sec-vandermonde>`

    The implementation of this function is left as an :ref:`exercise
    <ex-vandermonde>`.
    """

    totalcol = comb(degree + cell.dim, cell.dim)
    m = points.shape[0]

    if grad == False:
        Vmat = np.zeros((m, totalcol))

        if cell.dim == 1:
            for colnum in range(0, degree + 1):
                Vmat[:, colnum] = np.power(points[:, 0], colnum)

        else:
            for s in range(0, degree + 1):  #total power of monomial
                for q in range(0, s + 1):  #power for y
                    colnum = (s + 1) * (s) // 2 + q
                    Vmat[:, colnum] = np.power(points[:, 0], s - q) * np.power(
                        points[:, 1], q)

    else:  #grad == True
        Vmat = np.zeros((m, totalcol, cell.dim))

        if cell.dim == 1:
            for colnum in range(1, degree + 1):
                Vmat[:, colnum,
                     0] = colnum * np.power(points[:, 0], colnum - 1)

        else:
            for s in range(0, degree + 1):
                for q in range(1, s + 1):
                    #do for d/dx: x has power q
                    colnum = (s + 2) * (s + 1) // 2 - q - 1
                    Vmat[:, colnum,
                         0] = q * np.power(points[:, 0], q - 1) * np.power(
                             points[:, 1], s - q)

                    #do for d/dy: y has power q
                    colnum = (s + 1) * (s) // 2 + q
                    Vmat[:, colnum,
                         1] = q * np.power(points[:, 0], s - q) * np.power(
                             points[:, 1], q - 1)

    return Vmat
Ejemplo n.º 28
0
def throws(N_dices=10, n_faces=2):
    " faces go from 0 to n_faces"
    maximo = (n_faces - 1) * N_dices

    results = np.array(list(int(comb(N_dices, k)) for k in range(maximo + 1)))

    df_res = pd.DataFrame(results)
    df_res.columns = ["N° formas"]

    return df_res
Ejemplo n.º 29
0
def select(population, popFitness):
    probList = []
    maximumFitness = math.comb(len(population[0]), 2)

    for i in popFitness:
        probList.append(i / maximumFitness)
    while (True):
        randomPosition = random.randint(0, 7)
        if probList[randomPosition] >= mutation_threshold:
            return population[randomPosition]
Ejemplo n.º 30
0
def compute_direct(n, m, l):
    import math

    result = 0
    for i in range(m, n + 1):
        c = math.comb(i - 1, m - 1)
        d = (l - 1) ** (i - m)
        e = l ** (n - i)
        result += c * d * e
    return result