예제 #1
0
def solve(C, N):
    average = 0
    for m in range(1, 200):
        foo = 0
        for i in range(1, C + 1):
            foo += (-1)**(i + 1) * gmpy.comb(C, i) * A(N, C - i)**m
        p = A(N, C)**m - foo
        bar = 0
        for i in range(1, C + 1):
            bar += (-1)**(i + 1) * gmpy.comb(C, i) * A(N, C - i)**(m - 1)
        p = p - (A(N, C)**(m - 1) - bar) * A(N, C)
        average += (p / A(N, C)**m) * m
    return average
예제 #2
0
def get_number_combinations(tile_length, row_length=ROW_LENGTH):
    s = 0
    for num_tiles in range(1, row_length / tile_length + 1):
        total_tiles = row_length - (num_tiles * tile_length) + num_tiles
        comb = gmpy.comb(total_tiles, num_tiles)
        s += comb
    return s
예제 #3
0
def p053():
    sum = 0
    for n in tqdm(range(1, 101)):
        for r in range(1, n + 1):
            if (comb(n, r)) > 1000000:
                sum += 1
    print(sum)
예제 #4
0
def probs(post_state):
    """ Get all possible sub-states from post_state and their probabilities """

#    print 'not cached'
    
    s_prime= set()
    sub_states = [0]*len(post_state)
    #if post_state == (0,0,0):
    #    return {(0,0,0) : 0}
    '''
    For each element in the post state, figure out all ways it can be spread out.
    Example for (5,4,3):
    So figure out all the ways (5,0,0) can be spread out (4,1,0),(4,0,1),(3,2,0)...
    along with the probability of each new sub-state happening.
    Then recombine all the sub-states together to have every possible resulting
    state, and calculate the resulting probability of each distinct new state. 
    '''
    for pos in range(len(post_state)):
        sub_states[pos] = set()
        el = post_state[pos]
        if el == 0:
            sub_states[pos].add(((0,0,0), 1))
            continue
        '''
        Figure out all attainable states and their likelihood.
        I'm iterating through every possible state, and only saving those with
        the right total number of cows.
        A bit of base 13 trickery going on here, replace 13 by 10 and it'll make
        sense
        '''
        for s in states():
            if(sum(s) == el):
                p = t_probs[pos]
                #Calculate the probability of this state happening
                prob = (p[0]**s[0])*(p[1]**s[1])*(p[2]**s[2])
                #Correct the probability for states that can occur multiple ways
                prob *= comb(el, max(s)) #Uses combinations
                #If it's possible, save it
                if(prob > 0):
                    sub_states[pos].add((s, prob))
    #Now for combine all the sub_states together in every possible way
    new_states = [join_states(j_states) for j_states in cartesian_product(sub_states)]
    prebirth = concat_multiples(new_states)
    #Now calculate birth probabilities:
    postbirth = list()
    for state in new_states:
        #This returns all the different amounts of cows that can be produced, along with probability.
        offspring = breed(state[0][1])
        for off in offspring:
            if sum(state[0]) + off > H:
                calves = H - sum(state[0])
                num_young = state[0][0] + calves
            else:
                num_young = state[0][0] + off
            postbirth.append(((num_young, state[0][1], state[0][2]), 
                              state[1] * offspring[off]))

    ret_states = concat_multiples(postbirth)
    return ret_states
예제 #5
0
def scherbak(a):
 #a = reduce(a)
 s=int(sum(a)/2)+2
 end=len(a)
 subt=[]; t=[]
 for substring_len in range(1,end):
  it=list(range(substring_len))
  while it[0]<=end-substring_len-2:
   subt.append(0); subset=[a[i] for i in it]
   if sum(subset)+substring_len-s>=end-3:
    subt[-1]=int(comb(sum(subset)+substring_len-s, end-3))
   it=nextsubset(list(it), end)
  subt.append(0); subset=[a[i] for i in it]
  if sum(subset)+substring_len-s>=end-3:
   subt[-1]=int(comb(sum(subset)+substring_len-s, end-3))
  t.append(sum(subt)*(-1)**(end+1-substring_len)); subt=[]
 return(sum(t))
예제 #6
0
def binomial(k, n):
    """Return the number of combinations of k elements among a collection of
       size n."""
    if k < 0:
        return 0
    elif k > n:
        return 0
    else:
        return comb(int(n), int(k))
예제 #7
0
def scherbak(a):
  s=int(sum(a)/2)+2
  end=len(a)
  subt=[]; t=[]
  x=1 #Lengths of substrings being iterated
  while x<end:
    it=list(range(x))
    while it[0]<=end-x-2:
      subt.append(0); subset=[a[i] for i in it]
      if sum(subset)+x-s>=end-3:
        subt[-1]=int(comb(sum(subset)+x-s, end-3))
      it=nextsubset(list(it), end)
    subt.append(0); subset=[a[i] for i in it]
    if sum(subset)+x-s>=end-3:
      subt[-1]=int(comb(sum(subset)+x-s, end-3))
    t.append(sum(subt)*(-1)**(end+1-x)); subt=[]
    x+=1
  return(sum(t))
예제 #8
0
def main():
    """Main Program"""
    counter = 0
    for n in range(1, 101):
        for r in range(1, n):
            c = gmpy.comb(n, r)
            if c > 1000000:
                counter += 1
    print counter
예제 #9
0
def binomial(k, n):
    """Return the number of combinations of k elements among a collection of
       size n."""
    if k < 0:
        return 0
    elif k > n:
        return 0
    else:
        return comb(int(n), int(k))
예제 #10
0
def get_number_combinations(num_tiles=0, accum_tile_length=0, row_length=ROW_LENGTH):
    if accum_tile_length > row_length:
        return 0

    total_tiles = num_tiles + row_length - accum_tile_length
    s = gmpy.comb(total_tiles, num_tiles)
    for color_tile_length in ALL_COLORS:
        s += get_number_combinations(num_tiles + 1, accum_tile_length +
                                     color_tile_length)
    return s
def score(internal, degree, number_of_nodes, total_nodes):
    """
    Returns the score for a single community 
    """
    community_score = 0.
    external = degree - (2 * internal)
    if number_of_nodes == 0:
        return 0
    elif number_of_nodes == 1:
        return 0
    else:
        internal_density = internal / float(comb(number_of_nodes, 2))
    return internal_density
예제 #12
0
def pure(n, rank):
    answer = 0

    if rank == 1:
        return 1

    if (n, rank) in mem:
        return mem[(n, rank)]

    for i in xrange(1, rank):
        answer += pure(rank, i) * int(comb(n - rank - 1, rank - i - 1))

    mem[(n, rank)] = answer
    return answer
예제 #13
0
def score(internal, degree, number_of_nodes, total_nodes) :
    """
    Returns the score for a single community 
    """
    community_score = 0.
    external = degree - (2*internal)
    if number_of_nodes == 0 :
        pass
    elif number_of_nodes == 1 :
        pass
    else :
        separability = internal / float(internal + external)
        internal_density = internal / float(comb(number_of_nodes,2))
        community_score = separability * internal_density
    actual_score = (number_of_nodes / float(total_nodes)) * community_score
    return actual_score
예제 #14
0
def score(internal, degree, number_of_nodes, total_nodes) :
    """
    Returns the score for a single community 
    """
    community_score = 0.
    external = degree - (2*internal)
    if number_of_nodes == 0 :
        pass
    elif number_of_nodes == 1 :
        pass
    else :
        separability = internal / float(internal + external)
        internal_density = internal / float(comb(number_of_nodes,2))
        community_score = separability * internal_density
    actual_score = (number_of_nodes / float(total_nodes)) * community_score
    return actual_score
def membership_function(X_test,y_test,class_value,alpha,prior_probability,total_X_val):

    X_test = np.matrix(X_test)
    #print prior_probability
    #gjx = np.zeros(X_test.shape[0])

    gjx =[]


    for i in range(X_test.shape[0]):

        for j in range(X_test.shape[1]):
            sum_gj =0.0
            combination = gm.comb(int(total_X_val[i]),int(X_test[i,j]))
            if(combination!=0 and alpha[j]!=0 and (1-alpha[j])!=0):
                sum_gj+= (mt.log(combination)) + (X_test[i,j] * mt.log(alpha[j])) + ((total_X_val[i]-X_test[i,j]) * mt.log(1-alpha[j]))
            else:
                sum_gj+= 0

        sum_gj+= mt.log(abs(prior_probability))
        """j=1
        val1 = [(mt.log(gm.comb(int(total_X_val[j]),int(X_test[j,i])))) for i in range(X_test.shape[1])]
        val2 = sum([(X_test[j,i] * mt.log(alpha[i])) for i in  range(X_test.shape[1])])
        val3 = sum([((total_X_val[j] - X_test[j,i]) * mt.log(1-alpha[i])) for i in range(X_test.shape[1])])


        total = val1 + val2 + val3 + mt.log(prior_probability)
        print total_X_val[j]+1
        print X_test[j,18]
        print mt.log(gm.comb(1183,347))
        print "Val 1 :",val1
        print "Val 2 :",val2
        print "Val 3 :",val3
        print "Total :",total
        exit(0)"""
        gjx.append(sum_gj)







    return np.array(gjx)
예제 #16
0
def nbcomb(n, k):
    if k == 1 or k == n - 1:
        return 1

    if (n, k) in results.results:
        return results.results[(n, k)]

    answer = 0
    x = 1
    while x < k:
        val = nbcomb(k, x)
        answer += gmpy.comb(n - k - 1, k - x - 1) * val
        x += 1

    answer = int(answer) % 100003

    results.results[(n, k)] = answer

    return answer
예제 #17
0
def f(n, k):
    if n < 0 or k < 0:
        return 0
    if n <= k:
        return 0
    if n == k + 1:
        return 1
#    print "%d %d" % (n, k)

    if d[n][k] != -1:
        return d[n][k]

    res = 0

    t = n - k - 1
    for i in range(t + 1):
        res += f(k, k - i - 1) * comb(t, i)
        res %= MOD

    d[n][k] = res
    return res
예제 #18
0
#!/usr/bin/env python
import gmpy
count = 0
for n in range(1, 101):
    for r in range(1, n):
        c = gmpy.comb(n,r)
        if c > 1000000:
            count += 1
print count
예제 #19
0
def memoized_comb(x, n):
    if memoize_comb[x][n] == -1:
        memoize_comb[x][n] = comb(x, n) % MOD
    return memoize_comb[x][n]
예제 #20
0
def binomial(p, n, k):
    return gmpy.comb(n, k) * (pow(p, k)) * pow(1 - p, n - k)
예제 #21
0
def K1(p, q, tau, T):

#K1 function
#
# USAGE: [k1 k1d k1dd] = K1(p,q,tau,T)
#
# PARAMETERS:
#  p,q ~ Degree of the interpolation polynomial of the first and second
#       signals.
#  tau ~ Point (modulo T) in which the cross-correlation function is 
#       evaluated.
#  T ~ Sampling period of the discrete signals.
#
# RETURN VALUE:
#  k1,k1d,k1dd ~ Value of the function, the first and the second derivative
#       at tau respectively.
# 
# DESCRIPTION:
#     The K1 function corresponds to the following formula
#     k1 = sum_{p=0}^q choose(q,k) * (T-tau)^(q-k) * tau^(p+k+1) / (p+k+1)
#     and its derivatives (1st and 2nd) wigh respect to tau. T and tau may 
#     be two vectors of the same size, or vector and number.
#
# REFERENCES:
#     X. Alameda-Pineda and R. Horaud. Geometrically-constrained time delay
#     estimation-based sound source localisation (gTDESSL). Research Report 
#     RR-7988, INRIA, June 2012.
#
#     see also K2, CCInterpolation
# Copyright 2012, Xavier Alameda-Pineda
# INRIA Grenoble Rhone-Alpes
# E-mail: [email protected]
 
# This is part of the gtde program.
# 
# gtde is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

    ### Compute the function's value
    k1 = np.zeros((1,tau.size))
    for r in np.arange(0., q+1):
        k1 = k1 + gp.comb(q, int(r)) * (T-tau)**(q-r) * tau**(p+r+1.) / float(p+r+1.)
        
    ### Compute its first derivative
    k1d = np.zeros((1,tau.size))
    for r in np.arange(0., q):
        k1d = k1d + gp.comb(q, int(r)) * (T-tau)**(q-r-1.) * tau**(r+p) * ( T-(1.+p+q)*tau / float(r+p+1.) )
    # r = q may give some numerical problems, special formula
    k1d = k1d + tau**(q+p)
    
    
    ### Compute its second derivative
    k1dd = np.zeros((1,tau.size))
    # -----
    # r = 0
    # -----
    if p >= 1.:
        if q >= 2.:
            # Same formula
            r = 0.
            k1dd = k1dd + gp.comb(q, int(r)) * (T-tau)**(q-r-2.) * tau**(r+p-1.) * ( (r+p)*T**2. - 2.*(q+p)*T*tau + (q+p)*(q+p+1)*tau**2. / float(r+p+1.) )
        elif q == 1.:
            k1dd = k1dd - tau**(p-1) * ( p*(tau-T) + 2*tau )
            
        else:
            k1dd = k1dd + p*tau**(p-1)
    else:
        # Special cases
        if q >= 2.:
            k1dd = k1dd + q*(T-tau)**(q-2) * ( (q+1)*tau - 2*T )
        elif q == 1.:
            k1dd = k1dd-2.
            
    # -------
    # r = q-1, exists if q >= 1, but for q = 1, the r = q will take
    # care of it
    # -------
    if q >= 2.:
        k1dd = k1dd + q*tau**(q+p-2) * ( (q+p)*(T-tau) - (T+tau) )
    
    # -----
    # r = q, it exists for q >= 1, since for q = 0, r = q will take
    # care of it
    # -----
    if q >= 1.:
        k1dd = k1dd + (q+p)*tau**(q+p-1)
        
    # Intermediate terms
    for r in np.arange(1., (q-2.)+1):
        k1dd = k1dd + gp.comb(q, int(r)) * (T-tau)**(q-r-2.) * tau**(r+p-1.) * ( float((r+p)*T**2.) - 2*(q+p)*T*tau + (q+p)*(q+p+1.)*tau**2/float(r+p+1) )
            
    return [k1, k1d, k1dd]
예제 #22
0

with timer("scipy"):
    for i in range(0, 10000,100):
        for j in range(0,i,10):
            scipy_choose(i,j)

with timer("sympy"):
    for i in range(0, 10000,100):
        for j in range(0,i,10):
            sympy_choose(i,j)

with timer("gmpy"):
    for i in range(0, 10000,100):
        for j in range(0,i,10):
            comb(i,j)

with timer("choose1"):
    for i in range(0, 10000,100):
        for j in range(0,i,10):
            choose1(i,j)


# OverflowError: integer division result too large for a float
# with timer("choose2"):
#     for i in range(0, 10000,100):
#         for j in range(0,i,10):
#             choose2(i,j)

# tooooo slow
# with timer("choose3"):
예제 #23
0
def K2(p, q, tau, T):

    # K2   K2 function
    #
    # USAGE: [k2 k2d k2dd] = K2(p,q,tau,T)
    #
    # PARAMETERS:
    #  p,q ~ Degree of the interpolation polynomial of the first and second
    #       signals.
    #  tau ~ Point (modulo T) in which the cross-correlation function is
    #       evaluated.
    #  T ~ Sampling period of the discrete signals.
    #
    # RETURN VALUE:
    #  k2,k2d,k2dd ~ Value of the function, the first and the second derivative
    #       at tau respectively.
    #
    # DESCRIPTION:
    #     The K2 function corresponds to the following formula
    #     K2 = sum_{k=0}^q choose(q,k) * (tau)^(q-k) * ( T^(k+p+1) - tau^(k+p+1)) / (k+p+1)
    #     and its derivatives (1st and 2nd) wigh respect to tau. T and tau may
    #     be two vectors of the same size, or vector and number.
    #
    # REFERENCES:
    #     X. Alameda-Pineda and R. Horaud. Geometrically-constrained time delay
    #     estimation-based sound source localisation (gTDESSL). Research Report
    #     RR-7988, INRIA, June 2012.
    #
    #     see also K1, CCInterpolation

    # Copyright 2012, Xavier Alameda-Pineda
    # INRIA Grenoble Rhone-Alpes
    # E-mail: [email protected]
    #
    # This is part of the gtde program.
    #
    # gtde is free software: you can redistribute it and/or modify
    # it under the terms of the GNU General Public License as published by
    # the Free Software Foundation, either version 3 of the License, or
    # (at your option) any later version.
    #
    # This program is distributed in the hope that it will be useful,
    # but WITHOUT ANY WARRANTY; without even the implied warranty of
    # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    # GNU General Public License for more details.
    #
    # You should have received a copy of the GNU General Public License
    # along with this program.  If not, see <http://www.gnu.org/licenses/>.
    # Compute the function's value
    k2 = np.zeros((1, tau.size))
    for r in np.arange(0, q + 1):
        k2 = k2 + gp.comb(q, int(r)) * (-tau) ** (q - r) * (T ** (p + r + 1.0) - tau ** (p + r + 1.0)) / float(
            p + r + 1.0
        )

    #% If asked, compute its derivative
    k2d = np.zeros((1, tau.size))
    #% The general formula works for r < q
    for r in np.arange(0, q):
        k2d = k2d + gp.comb(q, int(r)) * (-tau) ** (q - r - 1.0) * (
            (r - q) * (T ** (r + p + 1.0) - tau ** (r + p + 1.0)) / float(r + p + 1.0) + tau ** (r + p + 1.0)
        )

    k2d = k2d - tau ** (q + p)

    #% If asked, compute its second derivative
    k2dd = np.zeros((1, tau.size))
    #% The general formula works for r < q-1
    for r in np.arange(0, q - 1):
        k2dd = k2dd + gp.comb(q, int(r)) * (-1.0) ** (q - r - 2.0) * (
            (1.0 + r - q)
            * (r - q)
            * (T ** float(p) * tau ** (q - 1.0) * (T / tau) ** (r + 1.0) - tau ** (q + p - 1.0))
            / float(r + p + 1.0)
            + (r - p - 2.0 * q) * tau ** (q + p - 1.0)
        )

    #% If both q and p are 0, do not add anything
    if q + p > 0.0:
        #% Term for r = q-1
        k2dd = k2dd + q * (q + p + 1.0) * tau ** (q + p - 1.0)
        #% Term for r = q
        k2dd = k2dd - (q + p) * tau ** (q + p - 1.0)

    return [k2, k2d, k2dd]
예제 #24
0
#!/usr/bin/env python
from gmpy import comb
print comb(2 * 20,20)
def binomial_exact(k, p, n):
    return gmpy.comb(n, k) * p**k * (1-p)**(n-k)
예제 #26
0
def A(k, n):
    return gmpy.comb(n, k) * gmpy.fac(k)
예제 #27
0
"""
What I did was stopped calculating when i first encountered > 1Million, and calculated manually from that point.
The different formula for even and odd "n", i found by observing nCr results from 23,24,25,26,27.
Using GMPY library with Python made this extremely fast. < 1ms
"""

from gmpy import comb
num = 0
for n in xrange(20,101):
    for r in xrange(1,n):
        if comb(n,r) > 1000000:
            # print n,
            if n%2: more = 2*(n/2 - r +1)
            else: more = 2*(n/2 - r) + 1
            num += more
            break
print num

# one-liner
from gmpy import comb
sum(2*(n/2 -r +1) if n%2  else 2*(n/2 -r)+1 for n in xrange(20,101) for r in xrange(1,n) if comb(n,r) > 1000000)
def bin_coef_sum(n):
    return sum(gmpy.comb(n, i) ** 2 for i in xrange(n+1))
예제 #29
0
#!/usr/local/bin/python

from __future__ import division
import gmpy

num = 0
for i in xrange(569):
    num += gmpy.comb(1000,i)

dem = 2**1000

print num/dem
예제 #30
0
#!/usr/bin/env python
from gmpy import comb
print comb(2 * 20, 20)