Exemple #1
0
def extrapolate(x, y, t, mode="forward"):

    # if sum(np.diff(x, n=2)) != 0:
    #     return None #check if the x spacing is constant
    #let's assume this is correct for computational quickness
    bino = lambda n, k: fact(n)/(fact(k)*fact(n-k))
    if len(x) == 1:
        return x[0]
    h = float(x[1]-x[0])
    derivatives = [0]*(len(y))

    if mode == "forward":
        f = lambda n, i, y: (-1)**i*bino(n,i)*y[n-i]
        x0 = x[0]
        derivatives[0]=y[0]
    else:
        f = lambda n, i, y: (-1)**i*bino(n,i)*y[-i-1]
        x0 = x[-1]
        derivatives[0] = y[-1]

    for n in range(1,len(y)):
        for i in range(0, n+1):
            # print(n, i, f(n, i, y, bino))
            derivatives[n] += f(n, i, y)
        derivatives[n] /= h**n
    return sum([derivatives[n]/fact(n)*(t-x0)**n for n in range(len(y))])
Exemple #2
0
def problem_53():
    from math import factorial as fact
    c=0
    for n in range(1,101):
        for r in range(1,n):
            if fact(n)/(fact(r)*fact(n-r))>1000000:c+=1
    return c
 def __ecMatch__(self, seq, ref):
     if len(ref)==0: # shitty lines
         return -100,0
         
     oneago = None
     thisrow = range(1, len(ref) + 1) + [0]
     for x in xrange(len(seq)):
         twoago, oneago, thisrow = oneago, thisrow, [0] * len(ref) + [x + 1]
         for y in xrange(len(ref)):
             delcost = oneago[y] + 1
             addcost = thisrow[y - 1] + 1
             subcost = oneago[y - 1] + (seq[x] != ref[y])
             thisrow[y] = min(delcost, addcost, subcost)
     # return thisrow[len(ref) - 1],len(ref)
     thisrow.pop() # eliminate last element
     n = thisrow.index(min(thisrow))+1
     #n = len(thisrow)-thisrow[-1::-1].index(min(thisrow)) 
     d = thisrow[n-1]
     # print seq
     # print ref
     # print thisrow
     # print d,n
     d = min(d,n)
     #n=max(d,len(seq))
     #print d,n
     err_lsc = d*log(self.err_p) + (n-d)*log(1.0-self.err_p) + log(fact(n))-(log(fact(d))+log(fact(n-d)))
     return err_lsc,n
Exemple #4
0
def GetChanceOfDominantTraits(organisms):
	totalOutcomes = 4.0 * fact(len(organisms)) / (2*fact(len(organisms)-2)) 
	totalDominantOutcomes = 0.0
	for i in range(0, len(organisms)-1):
		for j in range(i+1, len(organisms)):
			totalDominantOutcomes += CountDominantAleleCombos(organisms[i], organisms[j])
	return totalDominantOutcomes / totalOutcomes
Exemple #5
0
def findFactorialSum():
    factorials = [fact(x) for x in range(0, 10)] # pre-calculate products
    total_sum = 0
    for k in range(10, fact(9) * 7): # 9999999 is way more than its fact-sum
        if sum([factorials[int(x)] for x in str(k)]) == k:
            total_sum += k

    return total_sum
def main():
    from sys import stdin,stdout
    from math import factorial as fact
    from collections import Counter
    k = int(stdin.readline().strip())
    s = stdin.readline().strip()
    c = Counter(s)
    stdout.write(str(fact(k)/fact(len(filter(lambda x: x>1,c.values())))))
def Enum(x):
    
    res = 1
    
    for i in xrange(1,x+1):
        res += fact(x)/(fact(x-i)*fact(i))
    
    
    return res % 1000000
Exemple #8
0
def comb(n, k):
    if (k > n):
        return 0
    else:
        if (k == n):
            return 1
        else:
            #print(n)
            #print(k)
            return ((fact(n))/((fact(k))*(fact(n-k))))
Exemple #9
0
def run():
    count = 0
    for n in xrange(23, 101):
        r = 1
        fn = fact(n)
        while fn / fact(r) / fact(n - r) < 10**6:
            r += 1
        o = 2 * (int(n / 2) + 1 - r) - (1 if n % 2 == 0 else 0)
        count += o
    return count
Exemple #10
0
def sph_harm_large(m, n, az, el):
    """Compute spherical harmonics for large orders > 84

    Parameters
    ----------
    m : (int)
        Order of the spherical harmonic. abs(m) <= n

    n : (int)
        Degree of the harmonic, sometimes called l. n >= 0

    az: (float)
        Azimuthal (longitudinal) coordinate [0, 2pi], also called Theta.

    el : (float)
        Elevation (colatitudinal) coordinate [0, pi], also called Phi.

    Returns
    -------
    y_mn : (complex float)
        Complex spherical harmonic of order m and degree n,
        sampled at theta = az, phi = el

    Y_n,m (theta, phi) = ((n - m)! * (2l + 1)) / (4pi * (l + m))^0.5 * exp(i m phi) * P_n^m(cos(theta))
    as per http://dlmf.nist.gov/14.30
    Pmn(z) is the associated Legendre function of the first kind, like scipy.special.lpmv
    scipy.special.lpmn calculates P(0...m 0...n) and its derivative but won't return +inf at high orders
    """
    if _np.all(_np.abs(m) < 84):
        return scy.sph_harm(m, n, az, el)
    else:

        # TODO: confirm that this uses the correct SH definition

        mAbs = _np.abs(m)
        if isinstance(el, _np.ndarray):
            P = _np.empty(el.size)
            for k in range(0, el.size):
                P[k] = scy.lpmn(mAbs, n, _np.cos(el[k]))[0][-1][-1]
        else:
            P = scy.lpmn(mAbs, n, _np.cos(el))[0][-1][-1]
        preFactor1 = _np.sqrt((2 * n + 1) / (4 * _np.pi))
        try:
            preFactor2 = _np.sqrt(fact(n - mAbs) / fact(n + mAbs))
        except OverflowError:  # integer division for very large orders
            preFactor2 = _np.sqrt(fact(n - mAbs) // fact(n + mAbs))

        Y = preFactor1 * preFactor2 * _np.exp(1j * m * az) * P
        if m < 0:
            return _np.conj(Y)
        else:
            return Y
Exemple #11
0
def S(n):
  N = n+1
  numbers = [ i for i in range(N) ]
  r = ''
  p = 1000000-1
  for i in range(1, N):
    j = p // fact(N-i)
    p %= fact(N-i)
    r += str(numbers.pop(j))
    if p == 0:
      break
  for n in numbers:
    r += str(n)
  return r
def count_pairs(a):
    a.sort()
    cnt = 0
    repeat = 1
    for i in range(1, len(a)):
        if a[i-1] == a[i]:
            repeat += 1
        else:
            if repeat > 1:
                cnt += fact(repeat) / fact(repeat-2) # permutation (n 2)
            repeat = 1
    if repeat > 1:
        cnt += fact(repeat) / fact(repeat-2)
    return int(cnt)
Exemple #13
0
def problem_74():
    from math import factorial as fact
    cnt = 0
    c=0
    for i in xrange(1000000):
        c+= 1
        if not c%10000: print c,cnt
        l = []
        while i not in l:
            l.append(i)
            reduce(lambda a,b: a + fact(int(n)),string(i))
            i = sum([fact(int(n)) for n in str(i)])
        if len(l)==60:cnt+=1

    return cnt
Exemple #14
0
 def p0(self,Pb,Pj):
     xi_  = self.xi(Pb)
     eta_ = self.eta(Pj)
     t1   = self.S1(Pb)+self.S2(Pb)
     t2   = ((self.c**self.c/fact(self.c))*xi_**(self.ns)
                 *(1-eta_**(self.n-1-self.ns))/(1-eta_))
     return float(((t1+t2)**(-1)))
def get_random_ranks(permsize, samplesize):
    perms = fact(permsize)
    ranks = set()
    while len(ranks) < samplesize:
        ranks |= set( randrange(perms)
                      for r in range(samplesize - len(ranks)) )
    return ranks
Exemple #16
0
 def S5(self, Pb, Pj):
     t1 = (
         (self.c ** self.c / fact(self.c))
         * (self.xi(Pb) ** self.ns)
         * sum([self.eta(Pj) ** (k - self.ns) for k in range(self.ns, self.n)])
     )
     return float(t1)
 def __searchNbestNodeMatchRestricted__(self, segm_s, segm_best, valid_nodes, is_prefix):
     # TODO:
     segm = " ".join(segm_s).strip()
     n = len(segm)
     # max_lsc = float("-inf")
     # max_node = None
     
     nbest_nodes = []
     for n_idx in valid_nodes:
         covered_sent = self.__nodes__[n_idx].getCoveredString().strip()
         if not is_prefix or (is_prefix and covered_sent[0:3] == "<s>"): 
             covered_sent = covered_sent.replace("|UNK|UNK|UNK","").replace("<s>","").replace("</s>","").strip()
             d = Levenshtein.distance(segm,covered_sent)
             d = min(d,n)
             err_lsc = d*log(self.err_p) + (n-d)*log(1.0-self.err_p) + log(fact(n))-(log(fact(d))+log(fact(n-d)))
             itp_lsc = self.__nodes__[n_idx].getInsideLogScore()+self.__nodes__[n_idx].getOutsideLogScore()
             cur_lsc = itp_lsc+self.err_w*err_lsc #inside x outside x err**err_w
             # if cur_lsc > max_lsc:
             #     max_lsc = cur_lsc
             #     max_itp_lsc = itp_lsc
             #     max_node = n_idx
             if len(nbest_nodes)<=segm_best or cur_lsc>nbest_nodes[0][0]:
                 nbest_nodes.append((cur_lsc,itp_lsc,n_idx))
                 nbest_nodes = sorted(nbest_nodes)[-segm_best:]
                 #print nbest_nodes
     #return max_lsc,max_itp_lsc,max_node
     still_more_options = True
     if len(nbest_nodes)<segm_best:
         still_more_options = False
     return nbest_nodes[0],still_more_options
Exemple #18
0
 def __searchBestNodeMatch__(self, pref_s):
     if len(pref_s)==0:
         node=self.__nodes__[self.__init_node__]
         ec_lsc = node.getInsideLogScore()+node.getOutsideLogScore()
         return self.__init_node__,ec_lsc,ec_lsc
     
     pref = " ".join(pref_s).strip()
     n = len(pref)
     max_lsc = float("-inf")
     max_node = None
     ordered_keys = sorted(self.__nodes__)
     #inside x outside x err
     for n_idx in ordered_keys:
         covered_sent = self.__nodes__[n_idx].getCoveredString().strip()
         if covered_sent[0:3] == "<s>": #consider only nodes covering a prefix
             covered_sent = covered_sent.replace("|UNK|UNK|UNK","").replace("<s>","").replace("</s>","").strip()
             d = Levenshtein.distance(pref,covered_sent)
             d = min(d,n)
             err_lsc = d*log(self.err_p) + (n-d)*log(1.0-self.err_p) + log(fact(n))-(log(fact(d))+log(fact(n-d)))
             itp_lsc = self.__nodes__[n_idx].getInsideLogScore()+self.__nodes__[n_idx].getOutsideLogScore()
             cur_lsc = itp_lsc+self.err_w*err_lsc
             if cur_lsc > max_lsc:
                 max_lsc = cur_lsc
                 max_itp_lsc = itp_lsc
                 max_node = n_idx
                 # print "\n-----------------------"
             #     print pref,"#",covered_sent,"#",n,"->",d
             #     print max_lsc, max_itp_lsc, err_lsc
             #     print self.__nodes__[max_node]
             #     print "-----------------------\n"
             # else:
             #     print " -->","#"+covered_sent+"#",d,cur_lsc,itp_lsc,err_lsc
     return max_node,max_lsc,max_itp_lsc
def calc_loss_combinations(n, prob_down):
    total_loss = 0
    prob_up = 1.0 - prob_down
    total_probs = 0

    for i in xrange(1, n+1):
        combs = fact(n * 2) / (fact(n+i) * fact(n-i))
        prob = prob_up ** (n+i) * prob_down ** (n-i)
        single_loss = (i*2) * combs * (prob * 2)
        total_loss += single_loss
        print "combs: {}".format(combs)
        if i > 0:
            total_probs += (prob * 2 * combs)
        else:
            total_probs += (prob * combs)
    return total_loss, total_probs 
def unranker2(n, r, pi):
    while n > 0:
        n1 = n-1
        s, rmodf = divmod(r, fact(n1))
        pi[n1], pi[s] = pi[s], pi[n1]
        n = n1
        r = rmodf
    return pi
def ranker2(n, pi, pi1):
    if n == 1:
        return 0
    n1 = n-1
    s = pi[n1]
    pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1]
    pi1[s], pi1[n1] = pi1[n1], pi1[s]
    return s * fact(n1) + ranker2(n1, pi, pi1)
 def __searchNbestNodeMatchRestricted__(self, segm_s, segm_best, valid_nodes, first_isle):
     segm = " ".join(segm_s).strip()
     n = len(segm)
     #print "SN:",segm_s, segm_best, len(valid_nodes), first_isle
     
     nbest_nodes = []
     for n_idx in valid_nodes:
         covered_sent_s,inside_lsc = valid_nodes[n_idx]
         #print n_idx,covered_sent_s,inside_lsc
         # all nodes represent prefixes
         # "|||" symbol represents previous matching
         # search for node whith best EC score on the unmatched suffix
         if first_isle:
             covered_sent = " ".join(covered_sent_s).replace("|UNK|UNK|UNK","").replace("</s>","").strip()
             d = Levenshtein.distance(segm,covered_sent)
             d = min(d,n)
             err_lsc = d*log(self.err_p) + (n-d)*log(1.0-self.err_p) + log(fact(n))-(log(fact(d))+log(fact(n-d)))
             itp_lsc = self.__nodes__[n_idx].getInsideLogScore()+self.__nodes__[n_idx].getOutsideLogScore()
             cur_lsc = itp_lsc+self.err_w*err_lsc #inside x outside x err**err_w
             if len(nbest_nodes)<=segm_best or cur_lsc>nbest_nodes[0][0]:
                 nbest_nodes.append((cur_lsc,itp_lsc,n_idx,segm_s))
                 nbest_nodes = sorted(nbest_nodes)[-segm_best:]
                 #print "P",covered_sent,d,err_lsc,itp_lsc,cur_lsc
                 #print "P",nbest_nodes
         else:
             max_suffix_size = len(covered_sent_s)-covered_sent_s.index("|||")
             for suffix_size in range(1,max_suffix_size):
                 covered_sent = " ".join(covered_sent_s[-suffix_size:]).replace("|UNK|UNK|UNK","").replace("</s>","").strip()
                 d = Levenshtein.distance(segm,covered_sent)
                 d = min(d,n)
                 err_lsc = d*log(self.err_p) + (n-d)*log(1.0-self.err_p) + log(fact(n))-(log(fact(d))+log(fact(n-d)))
                 itp_lsc = self.__nodes__[n_idx].getInsideLogScore()+self.__nodes__[n_idx].getOutsideLogScore()
                 cur_lsc = itp_lsc+self.err_w*err_lsc #inside x outside x err**err_w
                 if len(nbest_nodes)<=segm_best or cur_lsc>nbest_nodes[0][0]:
                     out_str = covered_sent_s[:-suffix_size]+tuple(segm_s)
                     nbest_nodes.append((cur_lsc,itp_lsc,n_idx,out_str))
                     nbest_nodes = sorted(nbest_nodes)[-segm_best:]
                     #print "I",covered_sent,d,err_lsc,itp_lsc,cur_lsc
                     #print "I", nbest_nodes
     #print nbest_nodes
     #return max_lsc,max_itp_lsc,max_node
     #sys.exit()
     still_more_options = True
     if len(nbest_nodes)<segm_best:
         still_more_options = False
     return nbest_nodes[0],still_more_options
def pieinsky():
    c1 = Decimal(4)
    c2 = Decimal(1103)
    c3 = Decimal(26390)
    c4 = Decimal(396)
    c5 = Decimal(9801)
    # code formatted for readability (make it be one line)
    root8 = Decimal('2.82842712474619009760337744841939615'
                     '7139343750753896146353359475981464956'
                     '9242140777007750686552831454700276')
    i = Decimal(0)
    thesum = Decimal(0)
    while True:
    	term = (fact(c1*i)*(c2 + c3*i))/(pow(fact(i),4)*pow(c4,4*i))
    	thesum = thesum + term
    	yield 1/((root8/c5)*thesum)
    	i += 1
Exemple #24
0
def test_binomial():
    from operator import __eq__
    from math import factorial as fact
    assert isinstance(real_binomial(1, 1), float)
    for f, eq in ((binomial, __eq__), (real_binomial, approx_eq)):
        for n in xrange(20):
            for k in xrange(n + 10):
                if k > n:
                    assert eq(f(n, k), 0)
                else:
                    assert eq(f(n, k), fact(n) / fact(k) / fact(n - k))
                    if k > 0 :
                        assert eq(f(n, -k), 0)
    # To prove correct our implementation of the binomial coefficient
    # C(r, k) for real r, int k, we only need one non-integer test
    # case beyond our tests for r = integer n above.  This case shows
    # that we're not using floor division.
    assert approx_eq(real_binomial(-5.5, 2), 17.875)
Exemple #25
0
def main():
	N = readInt()

	if N <= 12:
		der = countDer(N)
		f = fact(N)
		res = (f - der) / f
		print('%.8f' % res)
	else:
		print('0.63212056')
Exemple #26
0
def ev(n, l, a):
    """Evaluate zernike polynomial (n,l)
    
    :param a: The array over which to evaluate, of form [ [x,y] ]
    
    Example: evalZern(2,0, numpy.moveaxis(numpy.mgrid[-1:1:64j, -1:1:64j], 0, -1) )
    
    """
    m=abs(l)
    nradterms= 1+ (n-m)//2
    radpowers= n - 2*numpy.arange(nradterms)
    radcoeffs= numpy.array(list(map(lambda s: (-1)**s * fact(n-s) / ( fact(s) * fact ( (n+m)/2 -s ) * fact( (n-m)/2 -s )),
                                    numpy.arange(nradterms))))
    r=numpy.hypot(a[...,0], a[...,1])
    phi=numpy.arctan2(a[...,1], a[...,0])
    v=numpy.zeros_like(r)
    for i in range(nradterms):
        v+=radcoeffs[i]*r**radpowers[i]
    if l>0:
        v*=numpy.cos(l*phi);
    elif l<0:
        v*=numpy.sin(-l*phi)
    return v
def test1(comment, unranker, ranker):
    n, samplesize, n2 = 3, 4, 12
    print(comment)
    perms = []
    for r in range(fact(n)):
        pi = identity_perm(n)
        perm = unranker(n, r, pi)
        perms.append((r, perm))
    for r, pi in perms:
        pi1 = init_pi1(n, pi)
        print('  From rank %2i to %r back to %2i' % (r, pi, ranker(n, pi[:], pi1)))
    print('\n  %i random individual samples of %i items:' % (samplesize, n2))
    for r in get_random_ranks(n2, samplesize):
        pi = identity_perm(n2)
        print('    ' + ' '.join('%2i' % i for i in unranker(n2, r, pi)))
    print('')
Exemple #28
0
def analyse(sLast, s, terms, power=0):
    """Recursive function to analyse the series."""
    # we are done if s is all zeros
    if set(s) == {0}:
        return prettyTerms(terms)
    # differences have not converged yet
    elif len(s) > 1 and not len(set(s)) == 1:
        return analyse(sLast, difference(s), terms, power + 1)
    # differences have converged
    elif len(set(s)) == 1 and not (terms and terms[-1][1] == power):
        coeff = s[0]/fact(power)
        terms.append((coeff,power))
        s = [x - coeff * i ** power for i, x in enumerate(sLast,1)]
        return analyse(s, s, terms)
    # failure
    else:
        return "Failed to analyse sequence."
def chain(n):
    l = [n]
    while True:
        tot = 0
        for d in str(n):
            tot += fact(int(d))

        if v.has_key(tot):
            for j in range( len( l ) ):
                v[ l[j] ] = len(l)-j+v[tot]
            return len(l)+v[tot]
        if l.count(tot):
            for j in range( len( l ) ):
                v[ l[j] ] = len(l)-j
            return len(l)
        else:
            l.append(tot)
            n=tot
Exemple #30
0
def w3j_000(L, l, lp):

    J = L + l + lp
    if J % 2 == 1:
        #print 'odd J\n'
        return 0.
    if l + lp < L:
        #print 'l + lp < L'
        return 0.
    if np.abs(l - lp) > L:
        #print 'abs(l - lp) > L'
        return 0.

    #lnfact1 = stirling(J-2.*L) + stirling(J-2.*l) + stirling(J-2.*lp) - stirling(J+1.)
    #lnfact2 = stirling(J/2.) - stirling(J/2.-L) - stirling(J/2.-l) - stirling(J/2.-lp)
    #res = (-1.)**(J/2.) * np.exp(0.5*lnfact1 + lnfact2)
    fact1 = fact(J-2*L) * fact(J-2*l) * fact(J-2*lp) / fact(J+1)
    fact2 = fact(J/2) / (fact(J/2-L) * fact(J/2-l) * fact(J/2-lp))
    res = (-1)**(J/2) * fact1**0.5 * fact2
    return res
Exemple #31
0
def n_choose_r(n, r):
    return fact(n) / (fact(r) * fact(n - r))
Exemple #32
0
def factorial(n):
    from math import factorial as fact
    return fact(n)
Exemple #33
0
from math import factorial as fact

tc = int(input())
for i in range(tc):
    m, n = [int(j) for j in input().split(" ")]
    print((fact(m + n) // (fact(m) * fact(n))) % 1000000007)
while True:
    ''' print('1. Fibo Series')
    print('2. Odd Series')
    print('3. Even or Odd')
    print('4. Factorial')
    print('5. Exit') '''

    print('1. Fibo Series', '2. Odd Series', '3. Even or Odd', '4. Factorial', '5. Exit', sep='\n')

    choice = int(input('Please enter ur choice: '))
    if choice == 1 or choice == 2 or choice == 3 or choice == 4:
        n = int(input('Enter n: '))

    if choice == 1:
        # fibo series till n
        # print(com.abc.lib.series.fibo_series(n=n))
        print(series.fibo_series(n=n))
    elif choice == 2:
        # odd series till n
        # print(com.abc.lib.series.odd_series(n=n))
        print(series.odd_series(n=n))
    elif choice == 3:
        # even or odd -> n
        print(even_odd(n=n))
    elif choice == 4:
        # factorial of number n
        # print(factorial(n))
        print(fact(n))
    else:
        # print(n) # this will not work if at the start the user chooses the option 5
        break # breaks out forcibly from the closest loop
Exemple #35
0
""" To find the number of combinations to choose k items from n items"""

from math import factorial as fact  # or use import math
""" n: 
        Total number of items
    k:
        Number of items to choose
    c:
        Number of combinations = n!/(k!*(n-k)!) """

n = int(input("Enter the total number of items: "))
k = int(input("Enter the number of items to choose: "))

c = (
    fact(n) / (fact(k) * fact(n - k))
)  # or use c = (math.factorial(n)/(math.factorial(k)*math.factorial(n-k)))

print(
    "The total number of combinations to choose {0} items from {1} items is {2}"
    .format(k, n, c))
Exemple #36
0
def generate_spherical_coeff(l, m, lx, ly, lz):
    j = (lx + ly - abs(m))
    if j % 2 == 0:
        j = int(j / 2)
    else:
        return 0.0

    prefactor = fact(2. * lx) * fact(2. * ly) * fact(2. * lz) * fact(l)
    prefactor = prefactor * fact(l - abs(m))
    prefactor = prefactor / (fact(2. * l) * fact(lx) * fact(ly) * fact(lz))
    prefactor = prefactor / fact(l + abs(m))
    prefactor = math.sqrt(prefactor)

    term1 = 0.0
    for i in range(int((l - abs(m)) / 2) + 1):
        term1 = term1 + binomial(l,i) * binomial(i,j) * \
                        math.pow(-1,i) * fact( 2*l - 2*i ) / \
                        fact( l - abs(m) - 2*i )

    term1 = term1 / math.pow(2, l) / fact(l)

    m_fact = 1.
    if m < 0:
        m_fact = -1.

    term2 = 0.0 + 0.0j
    for k in range(j + 1):
        z = cmath.exp(m_fact * math.pi / 2. * (abs(m) - lx + 2 * k) * 1.j)
        term2 = term2 + binomial(j, k) * binomial(abs(m), lx - 2 * k) * z

    val = prefactor * term1 * term2

    if abs(val.real) < 1e-10:
        val = 0.0 + val.imag * 1j
    if abs(val.imag) < 1e-10:
        val = val.real

    return val
        def Comb(n, p):
            from math import factorial as fact

            return fact(n) // fact(p) // fact(n - p)
Exemple #38
0
def number_of_permuations(lst, n):
    '''gets the number of permutations of the type corresponding to a partition. E.g. a partition [1,2] means
	"swap 2 numbers, leave one alone"'''
    res = 1
    for i in range(1, n + 1):
        a = lst.count(i)  #how many times is the number there?
        if a > 0:
            res = res * (i**a) * fact(a)
    return fact(n) // res


h = 12
w = 12
s = 2
total = 0
n = 0
for p in partitions(h):
    for q in partitions(w):
        nh = number_of_permuations(p, h)
        nw = number_of_permuations(q, w)
        exponent = 0
        for i in p:
            for j in q:
                exponent += gcd(i, j)

        total = total + nh * nw * s**exponent
        print(p, q)
total = total // fact(h) // fact(w)
print(total)
Exemple #39
0
def Solve():
    return (sum([int(x) for x in str(fact(100))]))
Exemple #40
0
def get_domain_matrix(start_time, fname="", **kwas):
    '''
    :param start_time: int indicating the earliest query the window should include
    :param **kwas: keyword arguments for vv.get_svl()
    :return: (m) matrix of client pairs vs domains,
             (fmt) list of domains

    other outputs:
        -> csv with pairs vs domains matrix (m)
        -> csv with list of domain pair correlations (corrs)
        -> csv with list of mean Jaccard for each domain (means)
    '''
    kwas['start_time'] = start_time
    kwas['return_ccache'] = False
    svl, fmt, anssets = vv.get_svl(**kwas)
    print "svl len", len(svl)
    combs = fact(len(svl)) / (fact(2) * fact(len(svl) - 2))
    m = np.zeros((combs, len(fmt)))
    p = 0
    for i in xrange(0, len(svl) - 1):
        a = svl[i]
        logger.warning(str(i) + ", " + str(a.get_id()))
        aset = dict()
        for dom in a:
            aset[dom] = set(a[dom])
        for j in xrange(i + 1, len(svl)):
            b = svl[j]
            for k in xrange(0, len(fmt)):
                dom = fmt[k]
                domtotal = sum([a[dom][z] for z in a[dom]]) + sum(
                    [b[dom][z] for z in b[dom]])
                overlap = aset[dom].intersection(b[dom])
                weight = 0
                for z in overlap:
                    weight += (a[dom][z] + b[dom][z])
                m[p, k] = weight / domtotal
            p += 1

    df.overwrite(plotsdir + "dommatrix" + fname + ".csv",
                 df.list2line(fmt) + "\n")
    df.append(plotsdir + "dommatrix" + fname + ".csv", df.list2col(m))

    C = np.corrcoef(m, rowvar=False)
    corrs = list()
    for i in xrange(0, len(fmt) - 1):
        for j in xrange(i + 1, len(fmt)):
            corrs.append((fmt[i] + "_" + fmt[j], C[i, j]))
    corrs = sorted([y for y in corrs if not math.isnan(y[1])],
                   key=lambda z: z[1])
    means = sorted(zip(fmt, np.mean(m, axis=0)), key=lambda z: z[1])

    df.overwrite(plotsdir + "domcorr" + fname + ".csv", df.list2col(corrs))
    df.overwrite(plotsdir + "dommean" + fname + ".csv", df.list2col(means))

    meand = dict(means)
    # get mean jaccard vs # IPs seen
    mj_ni = [(meand[dom], len(anssets[dom])) for dom in meand]
    d_mj_ni = sorted([(dom, meand[dom], len(anssets[dom])) for dom in meand],
                     key=lambda z: z[1])
    df.overwrite(plotsdir + "jaccard_vs_ipspace" + fname + ".csv",
                 df.list2col(d_mj_ni))

    fig, ax = plt.subplots(1, 1)

    colors = iter(cm.rainbow(np.linspace(0, 1, len(mj_ni))))
    for x, y in mj_ni:
        ax.scatter(x, y, color=next(colors))
    plt.xlabel("mean jaccard")
    plt.ylabel("# IPs observed")
    ax.grid(b=True, which='major', color='b', linestyle='-')
    ps.set_dim(fig, ax, ylog=True)
    filename = plotsdir + "jaccard_vs_ipspace" + fname
    fig.savefig(filename + '.png', bbox_inches='tight')
    fig.savefig(filename + '.pdf', bbox_inches='tight')
    plt.show()
    plt.close(fig)

    return m, fmt
Exemple #41
0
from math import factorial as fact
n = 5
o = 3
x = fact(n)/fact(o)

print(x)

y=5/3

print(x)
Exemple #42
0
def ways(n, r):
    return fact(n) / (fact(r) * fact(n - r))
Exemple #43
0
 def combination(self, n, r):
     return (fact(n) / (fact(n - r) * fact(r)))
Exemple #44
0
def nCr_rep(n, r):
    return fact(n + r - 1) // (fact(r) * fact(n - 1))
Exemple #45
0
def binomial(x, n, p=0.5):
    coef = fact(n) / (fact(x) * fact(n - x))
    binom = coef * (p**x) * (1 - p)**(n - x)
    return binom
 def coef(i, j, z):
     if i < j: return 0
     return fact(i) * z**(i - j) / fact(i - j)
Exemple #47
0
    tree.insert(15)
    tree.insert(13)
    print(tree.find(1))
    print(tree.find(12))
    ''' Following tree is getting created:
                    10
                 /      \
               5         12
              / \           \
            4     8          20
                 /          /
                7         15
                         /
                       13
    '''

    tree.preorder()
    tree.inorder()
    tree.postorder()
    print('\n\nAfter deleting 20')
    tree.delete(20)
    tree.inorder()
    tree.preorder()
    print('\n\nAfter deleting 10')
    tree.delete(10)
    tree.inorder()
    tree.preorder()

elem = int(input("\nHow many elements you want to enter in a binary tree : "))
result = fact(2 * elem) // (fact(elem + 1) * fact(elem))
print("There are {} possible structure for {} elements".format(result, elem))
Exemple #48
0
from math import factorial as fact

n, i = (int(i) for i in input().strip().split(' '))
groups = list()
for _ in range(i):
    a, b = (int(i) for i in input().strip().split(' '))
    new = True
    for group in groups:
        if a in group or b in group:
            group.add(a)
            group.add(b)
            new = False
            break
    if new:
        group = set()
        group.add(a)
        group.add(b)
        groups.append(group)

if n == 1:
    total = 1
else:
    total = fact(n) / (fact(2) * fact(n - 2))
    for group in groups:
        ng = len(group)
        total -= fact(ng) / (fact(2) * fact(ng - 2))

print(int(total))
def c(n, x):
    return fact(n) / (fact(n - x) * fact(x))
Exemple #50
0
max_time = 10000  #2000 / µ
debug_interval = max_time / 200
Ntr = 3  # number of simulations to run

# RUN SIMULATIONS
simulations = []
for i in range(Ntr):
    print(f"Running simulation {i}")
    sim = Simulation(max_time, λ, µ, c, debug_interval)
    sim.run()
    simulations.append(sim)
print(f'Finished simulating')

# 9: show average number of packets in system over time
ρ = λ / (c * µ)
pi_0 = 1 / (sum([(c * ρ)**k / fact(k)
                 for k in range(0, c)]) + (c * ρ)**c / (fact(c) * (1 - ρ)))
pi_c_plus = (c * ρ)**c / (fact(c) * (1 - ρ)) * pi_0
theor_avg_load = c * ρ + ρ / (1 - ρ) * pi_c_plus

plt.plot([0, max_time], [theor_avg_load] * 2, 'k-', linewidth=1)
for sim in simulations:
    debug_times = [ds.event_time for ds in sim.debugStats]
    cum_avg_loads = [ds.cum_avg_load for ds in sim.debugStats]
    plt.plot(debug_times,
             cum_avg_loads,
             '-',
             c=np.random.rand(3, ),
             linewidth=1)
plt.show()
Exemple #51
0
# -*- coding:utf-8 -*-
"""Project Euler problem 15"""

from math import factorial as fact

w = 20
h = 20

print("Answer: " + str(int(fact(w + h) / (fact(w) * fact(h)))))
Exemple #52
0
      ->a single python file containing set functions
   packages --> sub packages --> modules ---> function ---> statements


# In[18]:


import math
math.floor(123.45)


# In[20]:


from math import factorial as fact
fact(5)


# In[21]:


from math import gcd as fact
gcd(10,15)


# In[ ]:


### standard libraries
- file i/o
- regular expressions
Exemple #53
0
def nCr(n, r):
    return fact(n) / (fact(r) * fact(n - r))
Exemple #54
0
def calculate_odds(white_bc, red_bc):
    product = red_bc * fact(white_bc) / fact(white_bc - 5) / fact(5)
    return product
Exemple #55
0
def estimate_state(p, m, ghk):
    p_list = [p[:, :, i] + c * (p[:, :, 0] - m) / fact(i) for i, c in enumerate(ghk)]
    res = torch.stack(p_list).permute((1, 2, 0, 3))
    return res
Exemple #56
0
import math
from math import factorial as fact

print(math.sqrt(4))

# help(math)
# help(math.factorial)

print(math.factorial(5))

print(fact(5) // fact(2) * fact(3))

print(fact(100))

print(0b10)
print(0o10)
print(0x10)
print(int("10000", 3))

print(3e8)

print(1.616e-35)

print(float("nan"))
print(float("-inf"))

x = """This is 
a 
multiline string"""

print(x)
Exemple #57
0
from math import factorial as fact
c = int(input())
for i in range(c):
    m, n = map(int, input().split())
    print(fact(n) // fact(m) // fact(n - m))
Exemple #58
0
import math
from functools import reduce
from math import factorial as fact

import mates.mates
from mates.mates import factorial
from mates.mates import gcd
from mates.mates import to_square


print(fact(4))
print(math.factorial(5))
print(reduce(lambda n1, n2: n1 + n2, [1, 2, 3, 4, 5]))

print(factorial(5))
print(gcd(8, 19))
print(to_square(10))

print(mates.mates.gcd(8, 18))

 def coef(P, i, j):
     from math import factorial as fact
     if i >= len(P) or j > i: return 0
     return P[i] * (fact(i) // fact(j) // fact(i - j))
Exemple #60
0
# Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly
# 6 routes to the bottom right corner.
#
# How many such routes are there through a 20×20 grid?

# question rephrased: how many different combinations of 20 units can fill 40 spots?
# answer: 40 choose 20

########################################################################################################################

# simple method using equation of n!/k!(n-k)! with n = 40, k = 20

from math import factorial as fact

print(int(fact(40) / (fact(20) * fact(40 - 20))))

########################################################################################################################

# outputting pascal's triangle, max of a given row gives result of above equation

n = 41  # needed to get answer: 2^40, need middle term so 41 since odd

new_list = []
for i in range(1, n + 1):
    old_list = new_list
    new_list = []

    for _ in range(i):
        new_list.append(0)