def solve_problem(): counter = 0 for n in range(1, 101): for r in range(0, n+1): if fac(n)/fac(r)/fac(n-r) > 1000000: counter += 1 return counter
def predict_errors(n,ct_main,freq_main,kmer_size,error_rate): ''' predict kmer freq for kmers with exactly n errors ''' #how many possible error kmers are there #k-choose-n combinations of bases can be mutated #for each combination there are 3^n combinations of bases to mutate to #pos = 3.0**n * sp.misc.comb(kmer_size,n) pos = 3.0**n * fac(kmer_size) / (fac(n)*fac(kmer_size-n)) #probability of any one particular error kmer being generated #when the kmer is read #n bases misread as the particular error base #remainder of bases are not misread prob = (error_rate/3.0)**n * (1.0 - error_rate)**(kmer_size-n) freq = [0.0] * len(ct_main) #for every count in the error-free histogram for i,ct1 in enumerate(ct_main): mean = ct1 * prob val1 = freq_main[i] * pos * math.exp(-mean) #generate error predictions for every count in the error histogram for j,ct2 in enumerate(ct_main): #poisson for count ct2 #scaled by val1 'trials' #freq[j] += val1 * poisson(mean,ct2) freq[j] += val1 * mean**ct2 / fac(ct2) if ct2 == 170: break #fac(171) is too big to be a float return freq
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
def a_function(l, r, i, l_1, l_2, pa, pb, pc, g): e = 1 / (4*g) out1 = Binomial.coefficient(l, l_1, l_2, pa, pb) out2 = (-1)**i * fac(l) * pc**(l - 2*r - 2*i) * e**(r + i) out3 = fac(r) * fac(i) * fac(l - 2*r - 2*i) ans = (-1)**l * out1 * (out2/out3) return ans
def _significance_direct_on_off(n_on, n_off, alpha): """Compute significance directly via Poisson probability. Use this method for small n_on < 10. In this case the Li & Ma formula isn't correct any more. * TODO: add reference * TODO: add large unit test coverage (where is it numerically precise enough)? * TODO: check coverage with MC simulation * TODO: implement in Cython and vectorize n_on (accept numpy array n_on as input) """ from math import factorial as fac from scipy.stats import norm # Compute tail probability to see n_on or more counts probability = 1 for n in range(0, n_on): term_1 = alpha ** n / (1 + alpha) ** (n_off + n + 1) term_2 = fac(n_off + n) / (fac(n) * fac(n_off)) probability -= term_1 * term_2 # Convert probability to a significance significance = norm.isf(probability) return significance
def part_p(n,k): result = 0 for y in range(k, n+1): len_combs = fac(n)/(fac(n-y)*fac(y)) result+=len_combs print result%1000000
def mend_prob(gen, num): prog = 2**gen # number of progeny in that generation result = 0 for x in range(num, prog+1): #sum the cumulative probability of exactly num or greater individuals occuring result += ((fac(prog)/(fac(x)*fac(prog-x)))*.25**x*.75**(prog-x)) #formula for binomial probability return ("%.3f" % result) #round to 3 decimal places
def Hp_norm(p,k,l): s = 0 for i in range(p+1): for j in range(i+1): s = s + (k*pi)**(2*(i-j))*(l*pi)**(2*j)*fac(i)/(fac(j)*fac(i-j)) return sqrt(0.25*s)
def per_match(seq): au_count = 0 gc_count = 0 for nuc in seq: if nuc == 'A': au_count += 1 if nuc == 'G': gc_count += 1 result = fac(au_count)*fac(gc_count) print result
def free_path(start, end): """Given start and end coords, calculate the total number of paths, assuming all entries are unblocked --> (m + n)! / (m! * n!) where m = num rows, n = num cols and start and end are tuples of the form (row pos, col pos)""" # num rows m = end[0] - start[0] # num cols n = end[1] - start[1] return fac(m + n) / (fac(m) * fac(n))
def pn(self,n): """ Probability in "n" state, holding n > 0 and n <= k """ assert(n > 0 and n <= self.k) if n < self.c: return (pow(self.l, n) / (fac(n) * pow(self.m, n))) * self.p0() elif self.c <= n: return pow(self.l, n) / (pow(self.c, (n - self.c)) * fac(self.c) * pow(self.m, n)) * self.p0()
def successorTerm(t): C = lambda n, k: round(fac(n) / (fac(k) * fac(n - k))) if t.exponent == 0: return (t,) if t.exponent == 1: return (t, Term(t.coefficient, 0)) elif t.exponent > 1: return map( lambda z: Term(t.coefficient * C(z[0], z[1]), z[1]), zip(repeat(t.exponent, t.exponent + 1), range(t.exponent + 1)), # n # k )
def b_function(self, l, ll, r, rr, i, l_1, l_2, a_x, b_x, p_x, g_1, l_3, l_4, c_x, d_x, q_x, g_2): sigma = self.sigma pa_x = p_x - a_x pb_x = p_x - b_x qc_x = q_x - c_x qd_x = q_x - d_x c_x = p_x - q_x delta = (1/(4*g_1)) + (1/(4*g_2)) out1 = (-1)**l * sigma(l, l_1, l_2, pa_x, pb_x, r, g_1) * sigma(ll, l_3, l_4, qc_x, qd_x, rr, g_2) out2 = (-1)**i * (2 * delta)**(2 * (r + rr)) * fac(l + ll - 2*r - 2*rr) * delta**i * c_x**(l + ll - 2*(r + rr + i)) out3 = (4 * delta)**(l + ll) * fac(i) * fac(l + ll - 2*(r + rr + i)) ans = out1 * (out2 / out3) return ans
def cool_sentence(n, a, v): from math import factorial as fac sent_count = 0 if a < 8: for i in range(1, a + 1): sent_count += int(fac(a) / fac(a - i)) else: for i in range(1, 8): sent_count += int(fac(a) / fac(a - i)) return sent_count * n * v
def lotto(use_random_coupon): weeks_to_play = 10000000 max_val = 36 all_numbers = [x for x in range(1, max_val + 1)] coupon = [] if use_random_coupon: print("Using random generated coupon") coupon_rows = 10 row_len = 7 while len(coupon) < coupon_rows: row = sample(all_numbers, row_len) row.sort() coupon.append(row) else: print("using manually generated coupon") coupon = [ [5, 10, 12, 19, 24, 26, 30], [7, 11, 12, 23, 25, 32, 34], [7, 11, 13, 24, 25, 29, 31], [4, 10, 14, 15, 21, 25, 29], [5, 6, 10, 11, 17, 30, 32], [4, 5, 8, 9, 10, 16, 18], [6, 12, 14, 15, 26, 33, 36], [1, 7, 10, 12, 16, 19, 34], [2, 10, 21, 22, 27, 30, 34], [6, 9, 17, 22, 25, 27, 34]] coupon_rows = len(coupon) row_len = len(coupon[0]) wins = 0 for week in range(1, weeks_to_play + 1): win_row = sample(all_numbers, row_len) win_row.sort() for row in range(0, coupon_rows): matches = 0 for number in win_row: if number in coupon[row]: matches += 1 if matches == row_len: wins += 1 print('Jackpot! Row {} in week {} with {}' .format(row + 1, week, coupon[row])) else: print('Game over! You won {} times in {} years!' .format(wins, int(weeks_to_play * 7 / 365.25))) print('Your win ratio is 1 in {}' .format(int(weeks_to_play * coupon_rows / wins))) win_prob = int(fac(max_val) / (fac(row_len) * fac(max_val - row_len))) print('The mathematical win ratio is 1 in {}' .format(win_prob))
def uniquePaths(self, m, n): """ :type m: int :type n: int :rtype: int """ if m>n: tmp=m;m=n;n=tmp; if m==0: return 0 a=fac(n+m-2) b=fac(m-1) c=fac(n-1) return a/b/c
def prob(k,N): from fractions import Fraction as F from math import factorial as fac nCr = lambda n,r: int(fac(n)/(fac(r)*fac(n-r))) progeny_k = 2**k i = N prob_out = 0 while i <= progeny_k: prob_ = (F(1/4)**i * F(3,4)**(progeny_k-i)) * nCr(progeny_k,i) dummy = (F(1/4)**i * F(3,4)**(progeny_k-i)) prob_out += prob_ print(i,dummy,nCr(progeny_k,i),prob_,sep='\t') i+=1 return float(prob_out)
def p0(self): """ Probability in "0" state """ if not self.p0_optimizer: self.p0_optimizer = True acum = 0 for n in range(0, self.c): acum += pow(self.r, n) / fac(n) aux = ((pow(self.r, self.c))/(fac(self.c))) * (((1 - pow(self.rho, self.k - self.c + 1)) / (1 - self.rho))) self.p0_aux = 1 / (acum + aux) return self.p0_aux else: return self.p0_aux
def anagrams(s, v=10000): anagram_list = [] while len(anagram_list) < v and len(anagram_list) < fac(len(s)): candidate = ''.join(sample(s, len(s))) if candidate not in anagram_list: anagram_list.append(candidate) return anagram_list
def lq(self): """ Mean length og the tail """ a = (self.p0() * pow(self.r, self.c) * self.rho) / (fac(self.c) * pow(1-self.rho, 2)) b = 1 - pow(self.rho, self.k - self.c + 1) - ((1-self.rho) * (self.k - self.c + 1) * pow(self.rho, self.k - self.c)) return a * b
def ordered(string): from math import factorial as fac out = [] temp = times = 0 for i in xrange(9, 0, -1): times = 0 while True: if temp + fac(i) < 1000000: times += 1 temp += fac(i) print temp else: out.append(times) break l = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] for item in out: print l.pop(item)
def calculateFrohlichcoupling(n,m): """Calculate the Frohlich coupling from resonance Raman spectra. See alivisatos paper on resonance Raman of CdSe""" if material == 'CdS': m_e = 0.18 m_h = 0.51 a0 = 5.82E-10 ## Lattice constant (m) eps_bulk = 5.3 eps_0 = 8.7 bohr = 21.6 # bohr exciton radius (m) wLO = 2*pi*1240/(0.01/305)/h ### s-1 delta= 3.07 elif material == 'CdSe': m_e = 0.13 m_h = 0.45 a0 = 6.05E-10 ## Lattice constant (m) eps_bulk = 6.1 eps_0 = 9.3 bohr = 32.3 # bohr exciton radius (m) wLO = 2*pi*1240/(0.01/210)/h ### s-1 delta = 2.93 e=1.602E-19 # C h = 6.626E-36 #Js wLO = 2*pi*1240/(0.01/205)/h print wLO eps_bulk = 10.16 eps_0 = 1 bohr=1 w = (3*pi**2)**(1/3)*(a0/bohr) def L(i,j,x): return 1 x = linspace(0,w,1000) y = x**4*(2+x**2)**2*(1+x**2)**-4 sumy = sum(y)*w/1000 delta = 1.97*e**2/(a0*h*wLO)*(1/eps_bulk-1/eps_0)*(1/w) * sumy densitymatrix = np.sqrt(fac(n)/fac(m))*exp(-0.5*delta**2)*delta**(n-m)*L(m,n-m,delta**2) return densitymatrix
def get_representation_matrix(l, Group_Operation): """ this function computes the d matrix, as presented in "A fast and stable method for rotating spherical harmonic expansions", Journal of Computational Physics 228 (2009) 5621-5627 Note that the algorithm uses the explicit sum quoted as being from Wigner. This is known to be unstable, but we will hardly need to consider cases beyond l=2, and this algorithm seems the easiest to code. """ # The sign indicates if the operation is a pure rotation, or a rotation combined with inversion sign = N.linalg.det(Group_Operation) R = sign*Group_Operation # Only a pure rotation has Euler angles! alpha, beta, gamma = R_to_euler(R, 'zyz') co = N.cos(beta/2.) si = N.sin(beta/2.) D = D_matrix(l) m_range = N.arange(-l,l+1) for mp in m_range: for m in m_range: exp = N.exp(-1j*m*(alpha+gamma)) prefactor = (-1.)**(mp-m)*N.sqrt( fac(l+mp)*fac(l-mp)*fac(l+m)*fac(l-m) ) s_min = N.max( [0,m-mp]) s_max = N.min( [l+m,l-mp]) #print 'mp = %i, m = %i'%(mp,m) #print ' s_min = %i, s_max = %i'%(s_min,s_max) for s in N.arange(s_min,s_max+1): den = fac(l+m-s)*fac(s)*fac(mp-m+s)*fac(l-mp-s) e1 = 2*(l-s)+m-mp e2 = 2*s-m+mp D[mp][m] += prefactor*(-1.)**s*co**e1*si**e2/den*exp Representation_Matrix = sign**l * D.get_matrix() return Representation_Matrix
def p24(digits, num): result = [] n = len(digits) - 1 while n >= 0: facn = fac(n) idx = num / facn result.append(digits[idx]) digits = digits[:idx] + digits[idx+1:] num %= facn n -= 1 return ''.join(result)
def run(): facs = [fac(num) for num in range(0, 10)] curiousnums = [] for num in range(10, 1000000): cnum, nsum = num, 0 while cnum > 0 and nsum < num: nsum += facs[cnum % 10] cnum /= 10 if nsum == num and cnum == 0: curiousnums.append(num) print curiousnums print "The curious nums sum up to %s." % sum(curiousnums)
def ros_lia(k,N): # Given: Two positive integers k N . In this problem, we begin with Tom, # who in the 0th generation has genotype Aa Bb. Tom has two children in # the 1st generation, each of whom has two children, and so on. Each # organism always mates with an organism having genotype Aa Bb. # # Return: The probability that at least N Aa Bb organisms will belong to # the k-th generation of Tom's family tree (don't count the Aa Bb mates at # each level). Assume that Mendel's second law holds for the factors. # Aa Aa 100 # AA Aa aa 25-50-25 x Aa # AA Aa | AA Aa aa | Aa aa 25/2 25/2 | 25/2 50/2 25/2 | 25/2 25/2 # AA Aa aa : 25 50 25 p = .25 # pop = 2**k prob_atLeast = 0 for n in range(N,pop+1): prob_exact = 1.* fac(pop)/fac(n)/fac(pop-n) * p**n * (1-p)**(pop-n) prob_atLeast += prob_exact print (n, prob_exact, prob_atLeast) return prob_atLeast
def num_paths2(n,m): """ This functino calculates unique pathsusing a closed pformula O(1) m********a Method Each move moves one square To reach n,m on must move n+m times encode movement patter (path) as 0 for moving in m direction and 1 for moving in the n direction. There is a bijection form counting number of paths and number of n+m bit integers wiht n 1's and m 0's (n+k-1) ( n ) number of ways to select n items with replication from a set of k items n = n k = m + 1 (n+m) ( n ) """ return fac(n + m) / (fac(n) * fac(m))
def per_match(seq): a_count = 0 u_count = 0 g_count = 0 c_count = 0 for nuc in seq: if nuc == "A": a_count += 1 if nuc == "G": g_count += 1 if nuc == "U": u_count += 1 if nuc == "C": c_count += 1 if a_count == u_count: au_pair = fac(a_count) else: au_pair = fac(max(a_count, u_count)) / fac(max(a_count, u_count) - min(a_count, u_count)) if g_count == c_count: gc_pair = fac(g_count) else: gc_pair = fac(max(g_count, c_count)) / fac(max(g_count, c_count) - min(g_count, c_count)) result = au_pair * gc_pair print result
def split(self, name, score): '''Splits a tag, modifies the score of the parts if appropriate and decided whether to keep the base tag or not.''' if self.regex['dontsplit'].match(name): return None, None, True if '&' in name: return name.split('&'), score, False if ' ' in name: split = name.split(' ') if len(split) > 2: # length>2: split into all parts of length 2 tags = [] count = len(split) for i in range(count): for j in range(i + 1, count): tags.append(split[i].strip() + ' ' + split[j].strip()) count = 0.5 * fac(count) / fac(count - 2) return tags, score / count, False elif any([self.regex['filter_instrument'].match(x) or self.regex['filter_location'].match(x) or self.regex['splitpart'].match(x) for x in split]): return split, score, any([self.regex['filter_generic'].match(x) for x in split]) return None, None, True
def main(): fitdict, sindict = readfit() mutlist = sindict.keys() tradict = calc_trajectory(fitdict, mutlist) accdict = {} #accessible dict[mutation number][frequency of accessible path] = genotype count pathdict = {} #pathdict[mutation number][geno] = [path1,path2,...] path=[subgeno1,subgeno2...] pathdict[1] = {} for i in range(2, 5): pathdict[i] = {} for geno in tradict[i]: pathdict[i][geno] = [] for subgeno in tradict[i][geno]: if subgeno not in pathdict[i - 1]: pathdict[i][geno].append([subgeno]) else: pathdict[i][geno].extend( [[subgeno] + subpath for subpath in pathdict[i - 1][subgeno]]) for i in range(2, 5): accdict[i] = {} for geno in pathdict[i]: totalpath = fac(i) accpath = 0 for path in pathdict[i][geno]: _acc = 1 for j in range(len(path) - 1): subgeno = path[j] if fitdict[subgeno] > fitdict[path[j + 1]]: _acc = 0 if fitdict[geno] > fitdict[path[0]]: _acc = 0 if _acc == 1: accpath += 1 acc_freq = float(accpath) / totalpath if acc_freq not in accdict[i]: accdict[i][acc_freq] = 0 accdict[i][acc_freq] += 1 outfile = open('analysis/stringent_accessible_trajectory.txt', 'w') outfile.write('hamming_distance\taccessible_frequency\tgenotype_count\n') for i in range(2, 5): for freq in accdict[i]: outfile.write( str(i) + '\t' + str(freq) + '\t' + str(accdict[i][freq]) + '\n') outfile.close()
def getPermutation(self, n, k): """ :type n: int :type k: int :rtype: str """ from math import factorial as fac res = "" nums = [i for i in range(1, n + 1)] k = k - 1 for i in range(0, n): tmp_fac = fac(n - i - 1) index = k // tmp_fac res = res + str(nums[index]) print(nums, index, tmp_fac) nums.pop(index) k = k % tmp_fac return res
def filter(self, f_g, rcut, Gcut, l=0): Rcut = 100.0 N = 1024 * 8 r_x = np.linspace(0, Rcut, N, endpoint=False) h = Rcut / N alpha = 4.0 / rcut**2 mcut = np.exp(-alpha * rcut**2) r2_x = r_x**2 m_x = np.exp(-alpha * r2_x) for n in range(2): m_x -= (alpha * (rcut**2 - r2_x))**n * (mcut / fac(n)) xcut = int(np.ceil(rcut / r_x[1])) m_x[xcut:] = 0.0 G_k = np.linspace(0, pi / h, N // 2 + 1) from scipy.interpolate import InterpolatedUnivariateSpline if l < 2: f_x = InterpolatedUnivariateSpline(self.r_g, f_g)(r_x) else: a_g = f_g.copy() a_g[1:] /= self.r_g[1:]**(l - 1) f_x = InterpolatedUnivariateSpline( self.r_g, a_g)(r_x) * r_x**(l - 1) f_x[:xcut] /= m_x[:xcut] f_k = fsbt(l, f_x, r_x, G_k) kcut = int(Gcut / G_k[1]) f_k[kcut:] = 0.0 ff_x = fsbt(l, f_k, G_k, r_x[:N // 2 + 1]) / pi * 2 ff_x *= m_x[:N // 2 + 1] if l < 2: f_g = InterpolatedUnivariateSpline( r_x[:xcut + 1], ff_x[:xcut + 1])(self.r_g) else: ff_x[1:xcut + 1] /= r_x[1:xcut + 1]**(l - 1) f_g = InterpolatedUnivariateSpline( r_x[:xcut + 1], ff_x[:xcut + 1])(self.r_g) * self.r_g**(l - 1) f_g[self.ceil(rcut):] = 0.0 return f_g
def object_list(objects): """ Return the shortest Hamiltonian path through a collection of objects. This is calculated using a brute force method that is certainly not intented for real life use because for example going from ten to eleven objects will increase the running time elevenfold and even with caching expensive distance calculations this quickly becomes completely unworkable. But this routine is intended as our baseline algorithm that is meant to be replaced with an approximation algorithm that is 'good enough' for our purposes. """ @lru_cache() def distance_squared(a, b): return (objects[a].location - objects[b].location).length_squared def length_squared(chain): sum = 0.0 for i in range(len(chain) - 1): sum += distance_squared(chain[i], chain[i + 1]) return sum s = time() shortest_d2 = 1e30 shortest_chain = None n_half = fac(len(objects)) // 2 for i, chain in enumerate(perm(range(len(objects)))): if i >= n_half: break d2 = length_squared(chain) if d2 < shortest_d2: shortest_d2 = d2 shortest_chain = chain print("{n:d} objects {t:.1f}s".format(t=time() - s, n=len(objects))) return [objects[i] for i in shortest_chain]
def object_list(objects): """ Return the shortest Hamiltonian path through a collection of objects. This is calculated using a brute force method that is certainly not intented for real life use because for example going from ten to eleven objects will increase the running time elevenfold and even with caching expensive distance calculations this quickly becomes completely unworkable. But this routine is intended as our baseline algorithm that is meant to be replaced with an approximation algorithm that is 'good enough' for our purposes. """ @lru_cache() def distance_squared(a,b): return (objects[a].location-objects[b].location).length_squared def length_squared(chain): sum = 0.0 for i in range(len(chain)-1): sum += distance_squared(chain[i],chain[i+1]) return sum s = time() shortest_d2 = 1e30 shortest_chain = None n_half = fac(len(objects))//2 for i,chain in enumerate(perm(range(len(objects)))): if i >= n_half: break d2 = length_squared(chain) if d2 < shortest_d2: shortest_d2 = d2 shortest_chain = chain print("{n:d} objects {t:.1f}s".format(t=time()-s, n=len(objects))) return [objects[i] for i in shortest_chain]
def normalisation(self): """Calculates normalisation constant and stores in self.normalisation once called. Returns ------- self.normalisation_memo : float """ if self.normalisation_memo is None: x, y, z = self.integral_exponents out1 = ((2 * self.exponent) / pi)**(3 / 4) out2 = (8 * self.exponent)**(x + y + z) * fac(x) * fac(y) * fac(z) out3 = fac(2 * x) * fac(2 * y) * fac(2 * z) self.normalisation_memo = out1 * sqrt(out2 / out3) return self.normalisation_memo
def get_lexigraphic_permutation_n(s, n): """ Get the element at index n of the lexigraphically ordered set of permutations of s. """ distance = n # the distance left to the goal n p_indexes = [None for e in s ] # the indexes into s representing the permutations index_pool = [i for i, e in enumerate(s)] # the pool of indexes as used up cur_index = 0 while cur_index < len(s): permutation_counter = fac( len(s) - cur_index - 1) # how many permutations there are between steps at this counter p_index = distance // permutation_counter # how many permutation counts we can deal out without going over the limit p_indexes[cur_index] = index_pool.pop( p_index) # pop from the index pool into the permutation index distance -= p_index * permutation_counter # reduce by the distance we traveled cur_index += 1 return p_indexes
def count_states(H, N, capacity): # Calculate order of magnitude of number of states for system with # H floors and N elevators, each can load at most capacity passengers. # # Full calculation: all states. # Min calculation: only states with <=1 unassigned passengers. # # Min results (per H, N, capacity): # 40,8,8: 13+4+64+168+3~252 # 20,4,4: 5+2+15+36+3~61 # 10,2,4: 2+1+5+13+2~23 # 4,2,3: 1+1+2+6+1~11 # # Conclusion: # direct search in state-space (e.g. Value Iteration) # is impractical for any interesting configuration. # for each elevator - in which floor is it? locations = H**N # for each elevator - in which direction is it moving? directions = 3**N # for each elevator and each floor - # how many passengers are carried towards that floor? carried = sum([fac(H)/(fac(H-i)*fac(i)) for i in range(capacity+1)])**N # for each elevator and each pair of floors - # are there (should be how many...) passengers waiting # for the elevator to take them between the floors? waiting_full = (2**(H**2))**N waiting_min = sum([fac(H**2)/(fac(H**2-i)*fac(i)) for i in range(capacity+1)])**N # unassigned passengers: for each pair of floors, # how many passengers are waiting for assignment. new_full = 2**(H**2) new_min = H**2 + 1 states_full = [locations, directions, carried, waiting_full, new_full] states_min = [locations, directions, carried, waiting_min, new_min] print(sum([log(x) for x in states_full])) print([log(x) for x in states_full]) print(sum([log(x) for x in states_min])) print([log(x) for x in states_min])
def _main(): infile = open("codejam/test_files/Y13R5P1/A.in") ocle = fac(37) z = int(infile.readline()) for cas in xrange(1, z + 1): b, n = map(int, infile.readline().strip().split()) x = map(int, infile.readline().strip().split()) x += [0] * (37 - n) x.sort() cx = list(x) sx = sum(x) mx = x[-1] for i in xrange(1, 37): crem = x[i - 1] * i - sum(x[:i]) if b >= crem: cx.append(x[i - 1] + (b - crem) / i) cx = cx + [y - 1 for y in cx if y] cx = cx + [y + 1 for y in cx] cx = sorted(set(cx)) # cx = range(5000) best = 0 # print x # print cx for v in cx: cle = sum(1 for w in x if w <= v) req = cle * v - sum(w for w in x if w <= v) if req <= b and cle: for j in xrange(cle): if req + j <= b: bag = ((cle - j) * v - sum(x[:cle - j]) ) * 36 * ocle / (cle - j) - (req + j) * ocle best = max(best, bag) best = float(best) / ocle print 'Case #%d: %.15f' % (cas, best) infile.close()
def fun(n): from math import factorial as fac Sn = sum(map(lambda x: 1 / fac(x), range(n + 1))) return Sn
from math import factorial as fac print(fac(100000000))
"""This programs computes how many combinations are possible to be made from a collection of 'n' unique integers grouped under 'g' elements. You need to specify the length of the collection and how many elements at a time you want to group from the collection. The number of possible combinations will be printed.""" # pylint: disable=C0103 from math import factorial as fac message = "Hello! Please complete the length of the collection and the value of the group" set_message = "The collection length is:" group_message = "Specify the group length:" print(message) print(set_message) n = int(input()) print(group_message) g = int(input()) result = fac(n) / (fac(g) * fac(n - g)) print("The number of possible combinations is " + str(int(result)))
def binomial(n, k): try: binom = fac(n) // fac(k) // fac(n - k) except ValueError: binom = 0 return binom
import math # importing this style requried 'math.' to call any fuction inside the module. from math import pi # here u can directly use pi without any prefix of 'math.' from math import * # it works same as first one but here also u not need the prfix, just can directly call the function from math import factorial as fac # to change the name as per convenience print(math.pi) print(pi) print(factorial(4)) print(fac(4))
def p_poisson(self,x,la): return ((la**x))/((fac(x)))
from math import factorial as fac testcases = int(input()) for t in range(testcases): n, k = map(int, input().split()) l = list(map(int, input().split())) l.sort() q = l[:k] a = q.count(q[-1]) b = l.count(q[-1]) print(fac(b) // (fac(a) * fac(b - a)))
def lang_k_rec(available_o, available_n, k, x, possible): if available_n > 0: lang_k_rec(available_o, available_n - 1, k + 'N', x + 1, possible) if available_o > 0 and x > 1: lang_k_rec(available_o - 1, available_n, k + 'O', x - 1, possible) if available_o == 0 and available_n == 0: possible.append('NN' + k + 'O') def gen_lang(): possible_k = [[], [], [], [], []] for av in range(5): lang_k_rec(av, av, '', 2, possible_k[av]) possible_k[av].sort() return possible_k if __name__ == "__main__": ntotal = 0 possible_k = gen_lang() for av in range(5): print(possible_k[av]) l = len(possible_k[av]) print(l, 'words') n = 4**(1 + av) * (fac(6) // fac(4 - av)) * l ntotal += n print(n, 'possibilities\n') print(ntotal, 'total possibilities')
def main(): ans = sum(map(int,str(fac(100)))) return ans
def chance_exactly_k(k, n, p): """ Returns the success chance of an event with probability 'p' to occur exactly 'k' in 'n' trials. """ return (fac(n) / (fac(k) * fac(n - k))) * p**k * (1 - p)**(n - k)
def Nfac(p, q): return fac(N(p,q))
def binomial(x, y): try: binom = fac(x) // fac(y) // fac(x - y) except ValueError: binom = 0 return binom
def comb_num(n, k): num = fac(n) // (fac(n - k) * fac(k)) return num
def p_binomial_dropout(self,total_chains,x,s): try: return ((fac(total_chains))*(s**(total_chains-x)))/(fac(total_chains-x)) except: return 0
import math from math import factorial as fac print(math.sqrt(81)) print(fac(10))
jt_pairs = ['0' for i in range(junctions)] jj_connections = 0 for i in range(towns + junctions - 1): pairs = raw_input().split() #check if both if int(pairs[0]) > towns and int(pairs[1]) > towns: jj_connections += 1 elif int(pairs[0]) > towns or int(pairs[1]) > towns: if int(pairs[0]) > towns: jt_pairs[int(pairs[0]) - towns - 1] = int(jt_pairs[int(pairs[0]) - towns - 1]) + 1 else: jt_pairs[int(pairs[1]) - towns - 1] = int(jt_pairs[int(pairs[1]) - towns - 1]) + 1 from math import factorial as fac pc = 0 for i in jt_pairs: pc = pc * fac(int(i)) if pc == 0: pc += fac(int(i)) if jj_connections == 0: pc = pc / towns if jj_connections > 0: pc = pc * fac(jj_connections) print str(pc) + ' 1'
print(S) #%% from math import factorial f=1 for i in range(1,51): f*=i print(f) print(factorial(50)) #%% from math import factorial as fac from math import e S=0 for i in range(0,101): S+=1/fac(i) print(S) print(e) #%% for i in range(9): ligne="" for j in range(8-i): ligne+=" " for j in range(2*i+1): ligne+="*" print(ligne) #%% from math import factorial n=factorial(50)
n, k = map(int, input().split()) from math import factorial as fac print(fac(n) // (fac(k)*fac(n-k))) """ # lst = [1] # for i in range(1, n+1): # lst.append(lst[i-1]*i) # print(lst) # a = lst[n] # b = lst[k] * lst[n-k] # print(a//b) 이게 왜 안돼? """
def p_binomial_inclusion(self,n,m,f): return (fac(n+m)*(f**m)*((1-f)**n))/(fac(n)*fac(m))
import math from math import factorial from math import factorial as fac print(math.sqrt(81)) n = 100 k = 2 print(fac(n) // (fac(k) * fac(n - k))) print(fac(n)) # printed out put is a side effect of the function # not a return value print(len(str(fac(n)))) for target_list in [1, 2, 3]: print('!!!!!!!', target_list)
#!/usr/bin/env python3 ''' author: pjv9 problem: http://rosalind.info/problems/grph/ Given: An RNA string s of length at most 80 bp having the same number of occurrences of 'A' as 'U' and the same number of occurrences of 'C' as 'G'. Return: The total possible number of perfect matchings of basepair edges in the bonding graph of s. ''' import sys from Bio import SeqIO seq = str(list(SeqIO.parse(sys.stdin, 'fasta'))[0].seq) from math import factorial as fac print(fac(seq.count('U')) * fac(seq.count('G')))
simulation = False if simulation: runs = 200000 bingo = 0 for r in xrange(runs): target = set(random.sample(range(N), m)) callout = set(random.sample(range(N), k)) if target.issubset(callout): bingo += 1 print "Probability to match", m, "numbers with", k, "calls out of", N, "numbers (simulated):", float( bingo) / runs # probability for exactly i matches in a row total = 0 for i in range(m + 1): p = binomial(m, i) * fac(N - k) / float( fac(N - k - m + i)) * fac(k) / float(fac(k - i)) * fac(N - m) / float( fac(N)) print N, k, m, ': prob for exactly', i, 'matches =', p total += p print 'Total (just to check) =', total # probability for exactly i matches in a non-winning row (i.e we know matches are < m) total = 0 print '\nGiven a non winning row we have:' for i in range(m): p = binomial(m - 1, i) * fac(N - 1 - k) / float( fac(N - 1 - k - (m - 1) + i)) * fac(k) / float( fac(k - i)) * fac(N - 1 - (m - 1)) / float(fac(N - 1)) print N, k, m, ': prob for exactly', i, 'matches =', p total += p