def find_optimal_path_n(zumy_pos, final_dest): if zumy_pos.ndim == 2: zumy_number = np.shape(zumy_pos)[0] else: zumy_number = 1 return final_dest pair_list = range(zumy_number) possible_pairs_iter = permutations(pair_list) possible_pairs = np.asarray([np.asarray(elem) for elem in possible_pairs_iter]) pair_for_cross_iter = combinations(pair_list, 2) pair_for_cross = np.asarray([np.asarray(elem) for elem in pair_for_cross_iter]) possible_total_distance = np.zeros(math.factorial(zumy_number)) possible_cross = np.zeros(math.factorial(zumy_number)) for ii in range(math.factorial(zumy_number)): current_pair = possible_pairs[ii] for jj in range(zumy_number): possible_total_distance[ii] = possible_total_distance[ii] + \ get_distance(zumy_pos[jj], final_dest[current_pair[jj]]) for curr_pair_for_cross in pair_for_cross: possible_cross[ii] = possible_cross[ii] + \ check_crossing(zumy_pos[curr_pair_for_cross[0]], final_dest[current_pair[curr_pair_for_cross[0]]], zumy_pos[curr_pair_for_cross[1]], final_dest[current_pair[curr_pair_for_cross[1]]]) possible_total_penalty = 1000*possible_cross + possible_total_distance minimum_index = np.argmin(possible_total_penalty) best_pair = possible_pairs[minimum_index] new_final_dest_tuple = tuple(final_dest[order] for order in best_pair) new_final_dest = np.vstack(new_final_dest_tuple) return new_final_dest
def testSmall(data, repeat1, repeat2): # Check that the shuffling is along the first axis. # The order of the elements in each subarray must not change. # This takes long time so `repeat1` need to be small. for i in range(repeat1): ret = mx.nd.random.shuffle(data) check_first_axis_shuffle(ret) # Count the number of each different outcome. # The sequence composed of the first elements of the subarrays is enough to discriminate # the outcomes as long as the order of the elements in each subarray does not change. count = {} stride = int(data.size / data.shape[0]) for i in range(repeat2): ret = mx.nd.random.shuffle(data) h = str(ret.reshape((ret.size,))[::stride]) c = count.get(h, 0) count[h] = c + 1 # Check the total number of possible outcomes. # If `repeat2` is not large enough, this could fail with high probability. assert len(count) == math.factorial(data.shape[0]) # The outcomes must be uniformly distributed. # If `repeat2` is not large enough, this could fail with high probability. for p in itertools.permutations(range(0, data.size - stride + 1, stride)): err = abs(1. * count[str(mx.nd.array(p))] / repeat2 - 1. / math.factorial(data.shape[0])) assert err < 0.01, "The absolute error {} is larger than the tolerance.".format(err) # Check symbol interface a = mx.sym.Variable('a') b = mx.sym.random.shuffle(a) c = mx.sym.random.shuffle(data=b, name='c') d = mx.sym.sort(c, axis=0) assert (d.eval(a=data, ctx=mx.current_context())[0] == data).prod() == 1
def binomial_factorial(self,n,k): """Calculate binomial coefficient using math.factorial, for testing against binomial coefficients generated by other means.""" if n >= k: return int( round( math.factorial(n) / ( math.factorial(k) * math.factorial(n - k) ) ) ) else: return 0
def f_f(j): n=2*j r=n//2 num=math.factorial(n) den=math.factorial(n-r) * math.factorial(r) return num//den
def keyspace(n,m,k): lastterm = factorial(k) / (factorial(k - m)) result = int(n * comb(n,m,exact=True) * lastterm) return result
def __init__(self, f_center, samplerate, order=4, bw_factor=1.0): self.f_center = f_center self.samplerate = samplerate self.order = order self.bw_factor = bw_factor fc_erb = (GFB_L + self.f_center / GFB_Q) * self.bw_factor # equation (14), line 3 [Hohmann 2002]: a = np.pi * math.factorial(2.*order - 2.) * 2.**-(2.*order - 2.) b = math.factorial(order - 1.)**2 a_gamma = a / b # equation (14), line 2 [Hohmann 2002]: b = fc_erb / a_gamma # equation (14), line 1 [Hohmann 2002]: lamda = np.exp(-2*np.pi*b / samplerate) # equation (10) [Hohmann 2002]: beta = 2 * np.pi * f_center / samplerate # equation (1), line 2 [Hohmann 2002]: self.coef = lamda * np.exp(0 + 1j*beta) # normalization factor from section 2.2 (text) [Hohmann 2002]: self.normalization_factor = 2. * (1 - np.abs(self.coef)) ** order self.state = np.zeros(order, dtype=np.complex, order='c')
def n_choose_k(n, k): """Computes n choose k.""" if n < k: return 0 else: return factorial(n) / factorial(k) / factorial(n - k)
def __ClassShape(self, w, x, N1, N2, dz): # Class function; taking input of N1 and N2 C = np.zeros(len(x), dtype=complex) for i in range(len(x)): C[i] = x[i]**N1*((1-x[i])**N2) # Shape function; using Bernstein Polynomials n = len(w) - 1 # Order of Bernstein polynomials K = np.zeros(n+1, dtype=complex) for i in range(0, n+1): K[i] = factorial(n)/(factorial(i)*(factorial((n)-(i)))) S = np.zeros(len(x), dtype=complex) for i in range(len(x)): S[i] = 0 for j in range(0, n+1): S[i] += w[j]*K[j]*x[i]**(j) * ((1-x[i])**(n-(j))) # Calculate y output y = np.zeros(len(x), dtype=complex) for i in range(len(y)): y[i] = C[i] * S[i] + x[i] * dz return y
def choose(a, b): if b == 0 or a == b: return 1 else: numer = factorial(a) denom = factorial(b) * factorial(a-b) return numer//denom
def expand_power(u, n): if n < Number(0): return Number(1) / expand_power(_expand(u), abs(n)) if isinstance(n, Rational): largest_int = Number(int(floor(n.value))) m = n - largest_int return expand_product(u ** m, expand_power(u, largest_int)) if not isinstance(n, Integer): raise ValueError('n must be an integer, not {}'.format(repr(type(n)))) elif n < Number(0): raise ValueError('n must be > 0, not {}'.format(n)) if isinstance(u, Add): f = u.args[0] r = u - f s = Number(0) for k in range(n.value+1): c = Number(factorial(n.value)/(factorial(k) * factorial(n.value - k))) s = s + expand_product(c * f**Number(n.value-k), expand_power(r, Number(k))) return s else: return u**n
def probabilityOfKeepSet(keep_set): probability = math.factorial(len(keep_set)) for value in range(1,7): num_value_in_set = sum([1 for x in keep_set if x == value]) probability /= math.factorial(num_value_in_set) probability = float(probability)/6**len(keep_set) # Divide by all possible choices return probability
def naiveBayesMultinomial(value,frequency,adjustment = 1): if not value: return 0 lim = 80 if frequency > 92: return math.log(math.pow(value*adjustment,lim)/math.factorial(lim)) else: return math.log(math.pow(value*adjustment,frequency)/math.factorial(frequency))
def multCoeff(x): a = 0 b = 0 c = 0 d = 0 e = 0 f = 0 g = 0 h = 0 i = 0 for j in str(x): if j == '1': a += 1 elif j == '2': b += 1 elif j == '3': c += 1 elif j == '4': d += 1 elif j == '5': e += 1 elif j == '6': f += 1 elif j == '7': g += 1 elif j == '8': h += 1 elif j == '9': i += 1 num = factorial(a+b+c+d+e+f+g+h+i) den = factorial(a)*factorial(b)*factorial(c)*factorial(d)*factorial(e)\ *factorial(f)*factorial(g)*factorial(h)*factorial(i) return num/den
def fast_nth_perm(digits, n): #temporary storage variables curr_num = n - 1 result = "" #go through the digits from the biggest down (i.e. 9 to 0) for i in reversed(range(len(digits))): #do integer division to get the quotient of curr_num / i! quotient = curr_num / math.factorial(int(i)) #also get the remainder with mod remainder = curr_num % math.factorial(int(i)) #the quotient is the index of the current digit in the desired #permutation. Add it to the result. result += (digits[quotient]) # and remove it from the list of digits (each digit can only # appear once) digits = "%s%s" % (digits[:quotient], digits[quotient+1:]) #update curr num to be the remainder of the previous #curr_num's division. curr_num = remainder return result
def solve(self, cipher): """ Labeled permutation variants :param cipher: the cipher """ N, M = cipher return math.factorial(N+M-1)/math.factorial(N)/math.factorial(M-1)%MOD
def combsel(): i = 0 for n in range(1, 101): for r in range(1, n+1): if (math.factorial(n)/((math.factorial(r)*(math.factorial(n-r))))) > 1000000: i+=1 return i
def get_score(self, subtract_cards): same_form = 0 form_larger = 0 if self.straight: for i in range(0, 12 - len(self.cards)): and_cards = True for j in range(len(self.cards)): and_cards = and_cards and subtract_cards[(i + j)* 4 + self.cards[j].suit] if and_cards: same_form += 1 if self.cards[0].rank > i: form_larger += 1 else: for i in range(0, 12): and_cards = True for j in range(len(self.cards)): and_cards = and_cards and subtract_cards[i* 4 + self.cards[j].suit] if and_cards: same_form += 1 if self.cards[0].rank > i: form_larger += 1 count_rank_2 = 0 for j in range(12*4, len(subtract_cards)): if subtract_cards[j]: count_rank_2 += 1 if count_rank_2 >= len(self.cards): same_form += math.factorial(count_rank_2)/(math.factorial(count_rank_2 - len(self.cards)) * math.factorial(len(self.cards))) return same_form if same_form == 0 else form_larger * 1.0/same_form
def digitFactorials(): sum = 0 for i in range(0, 10): for j in range(0, 10): for k in range(0, 10): for l in range(0, 10): for m in range(0, 10): for n in range(0, 10): for o in range(0, 10): digitSum = math.factorial(i) + math.factorial(j) + math.factorial(k) + math.factorial(l) + math.factorial(m) + math.factorial(n) + math.factorial(o) if i == 0: digitSum -= 1 if i == 0 and j == 0: digitSum -= 1 if i == 0 and j == 0 and k == 0: digitSum -= 1 if i == 0 and j == 0 and k == 0 and l == 0: digitSum -= 1 if i == 0 and j == 0 and k == 0 and l == 0 and m == 0: digitSum -= 1 if i == 0 and j == 0 and k == 0 and l == 0 and m == 0 and n == 0: digitSum -= 1 num = i*1000000 + j*100000 + k*10000 + l*1000 + m*100 + n*10 + o if num == digitSum and num != 1 and num != 2: print num sum += num
def count(self, N): # Is amazing easy the algoritm when understand. Is essential visualize # the structure of data, in this case, you should imagine than the SMN # is a line path that cross all points, without returning to one, after # having gone through. #Assume that N = 4 . Then there exists an MTF that follows the path ABCD, # with distance 2, 2 , 2, where A, B , C , D are the vertices. There is # also an MTF which follows the route ABDC with 2-2-2 away . These two # SMN share the same structure , the only thing that varies is the # order of the points. If you look , all combinations with 1-1-1 equals # the number of combination between two points is calculated as the # permutation of 4 points, must be reduced by half because the lines # connecting the vertices are unidirectional. numerodecombinaciones = math.factorial(N) / 2 SMNs = list(itertools.product(reversed(range(1, 3)), repeat = (N - 1))) waystotal = 0 for SMN in SMNs: waysSMN = 1 for i in range(N): for j in range(i +2, N): ways = 2 for k in range(i, j): if SMN[k] == 2: ways = 1 waysSMN *= ways waysSMN %= 1000000007 waystotal += waysSMN waystotal %= 1000000007 waystotal *= math.factorial(N) / 2 waystotal %= 1000000007 return waystotal
def nSphereVolume(n): ''' Calculate the volume of a unit n-sphere. TYPICAL USAGE ============= >>> nSphereVolume(0) 1 >>> nSphereVolume(1) 2 >>> nSphereVolume(2)/pi 1.0 >>> nSphereVolume(3)/(pi**2) 0.5 REFERENCES ========== Equation 5.19.4, NIST Digital Library of Mathematical Functions. http://dlmf.nist.gov/, Release 1.0.6 of 2013-05-06. @param n: dimension of the n-sphere @type n: int @return: volume of the unit n-sphere @rtype: ''' if n%2 == 0: d = n/2 return(pi**d/factorial(d)) else: d = (n-1)/2 return((2*((4*pi)**d)*factorial(d))/(factorial(2*d+1)))
def numtobasef(num,l): # computes the l-"digit" "base" factorial representation of num # there's probably a real name for this basef=[0]*l for i in range(l): basef[i]=num/factorial(l-i) num-=basef[i]*factorial(l-i) return basef
def GetWaveFunction(n,l,m,x,y,z): r = lambda x,y,z: numpy.sqrt(x**2+y**2+z**2) theta = lambda x,y,z: numpy.arccos(z/r(x,y,z)) phi = lambda x,y,z: numpy.arctan2(y,x) #phi = lambda x,y,z: numpy.arctan(y/x) a0 = 1. R = lambda r,n,l: numpy.sqrt(((2.0/n/a0)**3)*(math.factorial(n-l-1))/(math.factorial(n+l))/2/n)*(2*r/n/a0)**l * numpy.exp(-r/n/a0) * scipy.special.genlaguerre(n-l-1,2*l+1)(2*r/n/a0) #R = lambda r,n,l: (2*r/n/a0)**l * numpy.exp(-r/n/a0) * scipy.special.genlaguerre(n-l-1,2*l+1)(2*r/n/a0) WF = lambda r,theta,phi,n,l,m: R(r,n,l) * scipy.special.sph_harm(m,l,phi,theta) absWF = lambda r,theta,phi,n,l,m: abs((WF(r,theta,phi,n,l,m))**2) wf = WF(r(x,y,z),theta(x,y,z),phi(x,y,z),n,l,m) w = absWF(r(x,y,z),theta(x,y,z),phi(x,y,z),n,l,m) w[numpy.isnan(w)]=0 #wf[numpy.isnan(wf)]=0 phase = numpy.angle(wf) realwf = numpy.imag(wf)*10 #realwf = numpy.fabs(numpy.real(wf)*10)# need to by 10 because of the pg.isosurface() function #phase = numpy.array(w) #xsize = w.size/w[0].size #ysize = w[0].size/w[0][0].size #zsize = w[0][0].size #for i in range(0,xsize): # for j in range(0,ysize): # for k in range(0,zsize): # #angular = numpy.arctan2(wf[i][j][k].imag,wf[i][j][k].real) # #if angular < 0: # # phase[i][j][k] = angular+2*numpy.pi # #else: # # phase[i][j][k] = angular # phase[i][j][k] = numpy.arctan2(wf[i][j][k].imag,wf[i][j][k].real) phase[numpy.isnan(phase)]=0 realwf[numpy.isnan(realwf)]=0 return w,phase, realwf
def test_factorial(): """ Tests the factorial function. """ # DONE: 3a. Implement this function, using it to test the NEXT # function. Write the two functions in whichever order you prefer. # Include at least 4 tests. # # ** Use the math.factorial function as an ORACLE for testing. ** print() print('--------------------------------------------------') print('Testing the factorial function:') print('--------------------------------------------------') actual_answer = factorial(5) oracle_answer = math.factorial(5) test_case = 'factorial(5). Actual, Oracle answers:' print(' Called ', test_case, actual_answer, oracle_answer) actual_answer = factorial(8) oracle_answer = math.factorial(8) test_case = 'factorial(8). Actual, Oracle answers:' print(' Called ', test_case, actual_answer, oracle_answer) actual_answer = factorial(11) oracle_answer = math.factorial(11) test_case = 'factorial(11). Actual, Oracle answers:' print(' Called ', test_case, actual_answer, oracle_answer) actual_answer = factorial(14) oracle_answer = math.factorial(14) test_case = 'factorial(14). Actual, Oracle answers:' print(' Called ', test_case, actual_answer, oracle_answer)
def check_topological_embedding_brute(self, verbose=False): ''' Brute-force combinatoric method to check topological embedding ''' # Clear table and nodemap: self.T = { superN:{ subN:None for subN in self.subD.nodes } for superN in self.superD.nodes } self.AB_nodemap = None N = len(self.subD.nodes) # number of subdesign nodes if len(self.superD.nodes) < N: # shortcut - fewer nodes in superdesign self.AB_nodemap = None return False # compute number of matchings: num_matchings = math.factorial(len(self.subD.nodes))*math.factorial(len(self.superD.nodes)) count = 0 for sub_perm in permutations(self.subD.nodes): for super_perm in permutations(self.superD.nodes, N): #sys.stdout.write("%d \r" % count ) #sys.stdout.flush() # carriage returns don't work in Eclipse :-( if verbose: print str(count) + " / " + str(num_matchings) count += 1 self.AB_nodemap = dict (zip(sub_perm, super_perm)) if self.check_vertex2vertex(): if self.check_edge2path(): if self.check_vertex_disjointness(): return True # no embedding found. self.AB_nodemap = None return False
def odf_sh(self): r""" Calculates the real analytical ODF in terms of Spherical Harmonics. """ # Number of Spherical Harmonics involved in the estimation J = (self.radial_order + 1) * (self.radial_order + 2) // 2 # Compute the Spherical Harmonics Coefficients c_sh = np.zeros(J) counter = 0 for l in range(0, self.radial_order + 1, 2): for n in range(l, int((self.radial_order + l) / 2) + 1): for m in range(-l, l + 1): j = int(l + m + (2 * np.array(range(0, l, 2)) + 1).sum()) Cnl = ( ((-1) ** (n - l / 2)) / (2.0 * (4.0 * np.pi ** 2 * self.zeta) ** (3.0 / 2.0)) * ((2.0 * (4.0 * np.pi ** 2 * self.zeta) ** (3.0 / 2.0) * factorial(n - l)) / (gamma(n + 3.0 / 2.0))) ** (1.0 / 2.0) ) Gnl = (gamma(l / 2 + 3.0 / 2.0) * gamma(3.0 / 2.0 + n)) / \ (gamma(l + 3.0 / 2.0) * factorial(n - l)) * \ (1.0 / 2.0) ** (-l / 2 - 3.0 / 2.0) Fnl = hyp2f1(-n + l, l / 2 + 3.0 / 2.0, l + 3.0 / 2.0, 2.0) c_sh[j] += self._shore_coef[counter] * Cnl * Gnl * Fnl counter += 1 return c_sh
def n_choose_k(n: int, k: int) -> int: """ Return the binomial coefficient for n choose k. The binomial coefficient is defined as: n choose k = n! / (k!(n-k)!) For a number of objects n, which k choices allowed, this function reports the number of ways to make the selection if order is disregarded. We define n choose k == 0 for k > n. Args: n (int): A positive integer indicating the possible number of items to select. k (int): A positive integer indicating the number of items selected. Returns: int: The result of n choose k. Raises: ValueError: if n or k are not non-negative integers. """ # Check that n and k are allowed if not countable.is_nonnegative_integer(n): raise ValueError("n is a not a non-negative integer") if not countable.is_nonnegative_integer(k): raise ValueError("k is a not a non-negative integer") # We define n choose k for k > n as 0, that is, there are no way # to choose more items than exist in a set. if k > n: return 0 # Compute and return return math.factorial(n) // (math.factorial(k) * math.factorial(n - k))
def basis(coords,b1,b2,nmax): hermites = np.loadtxt('hermite_coeffs.txt') xrot = coords[:,0]/b1 yrot = coords[:,1]/b2 npix = coords.shape[0] all_basis = np.zeros((npix,nmax+1,nmax+1)) gauss = np.exp(-0.5*(np.array(xrot)**2+np.array(yrot)**2)) n1 = 0 n2 = 0 for n1 in range(0,nmax): n2 = 0 while (n1+n2) <= nmax: norm = m.sqrt(m.pow(2,n1+n2)*m.pi*b1*b2*m.factorial(n1)*m.factorial(n2)) k=0 h1=0. h2=0. while (k <= n1): h1 = h1+hermites[n1, k]*(np.array(xrot))**(n1-k) k=k+1 k=0 while (k <= n2): h2 = h2+hermites[n2, k]*(np.array(yrot))**(n2-k) k=k+1 all_basis[:, n1, n2] = gauss/norm*h1*h2; n2 = n2+1 return all_basis
def dig_fact(): # import timeit and start timer to measure time of function import timeit start = timeit.default_timer() import math # import math package for factorial function sum_total = 0 # initialize sum variable to hold sum of digit factorials list = [] # initalize list to hold all numbers which are equal to the sum of the factorial of their digits for i in range(3,math.factorial(9)*7): # iterate through range and check conditions per problem sum_total = 0 # reset sum variable for each number in range above for j in range(0,len(str(i))): # iterate through each digit of number in range above sum_total += math.factorial(int(str(i)[j])) # add factorial of each digit of number to "sum" variable for checking problem condition below if i == sum_total: # append number to list if it is equal to the sum of the factorial of its digits list.append(i) print sum(list) # return solution # stop timer and print total elapsed time stop = timeit.default_timer() print "Total time:", stop - start, "seconds"
def g_statistic(X, p=None, idx=None): """ return g statistic and p value arguments: X - the periodicity profile (e.g. DFT magnitudes, autocorrelation etc) X needs to contain only those period values being considered, i.e. only periods in the range [llim, ulim] """ # X should be real X = abs(numpy.array(X)) if p is None: power = X.max(0) idx = X.argmax(0) else: assert idx is not None power = X[idx] g_obs = power/X.sum() M = numpy.floor(1/g_obs) pmax = len(X) result = numpy.zeros((int(M+1),), float) pmax_fact = factorial(pmax) for index in xrange(1, min(pmax, int(M))+1): v = (-1)**(index-1)*pmax_fact/factorial(pmax-index)/factorial(index) v *= (1-index*g_obs)**(pmax-1) result[index] = v p_val = result.sum() return g_obs, p_val
def tabela(n): somatorio = lambda termo: sum(termo(float(i)) for i in xrange(n)) mysin = lambda x: somatorio(lambda i: (x ** (2 * i + 1)) * (-1) ** i / factorial(2 * i + 1)) mycos = lambda x: somatorio(lambda i: (x ** (2 * i)) * (-1) ** i / factorial(2 * i)) mytan = lambda x: mysin(x) / mycos(x) mypi = somatorio(lambda k: 4 * (-1) ** k / (2 * k + 1)) mye = somatorio(lambda k: 1.0 / factorial(k)) mypie = mypi / mye # calcular valores valores = [ ['n={0}'.format(n), 'Ve', 'Va', 'Eabs', 'Erel'], ['pi', pi, mypi], ['e', e, mye], ['pi/e', pie, mypie], ['sen(pi/e)', sin(pie), mysin(mypie)], ['cos(pi/e)', cos(pie), mycos(mypie)], ['tg(pi/e)', tan(pie), mytan(mypie)], ] # calcular erros for v in valores[1:]: ve, va = v[1], v[2] eabs = ve - va erel = eabs / ve v.append(eabs) v.append(erel) # imprimir tabela e uma linha em branco print_table(valores) print
def comb(n, r): if n == r: return 1 elif n < r: return 0 return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))
def __init__(self, n): self.n = n self.search_space_size = math.factorial(n) self.solution_size = n self.max_leave_out = self.solution_size - 1
(lunches == 'no food truck').all(axis=1).mean() # How likely is it that a food truck will show up sometime this week? 1 - (3 * .3**7) ((np.random.random((trials, 3)) > travis_park_food_truck).sum(axis=1) == 0).sum()/trials (lunches == 'food truck').any(axis=1).mean() # 8. If 23 people are in the same room, what are the odds that two of them # share a birthday? What if it's 20 people? 40? # (365! / (365 - 23)!) / (365^23) import math 1 - ((math.factorial(365) / math.factorial(365-23)) / 365**23) 1 - ((math.factorial(365) / math.factorial(365-20)) / 365**20) 1 - ((math.factorial(365) / math.factorial(365-40)) / 365**40) birthdays = pd.DataFrame(np.random.randint(1, 365, (10_000, 23))) birthdays.count(axis=1) birthdays birthdays.iterrows() birthdays.iloc[0, :] birthdays[birthdays.nunique(axis=1) == birthdays.count(axis=1)].count()/trials #or (birthdays.nunique(axis=1) == birthdays.count(axis=1)).mean() # with numpy birthdays = (np.random.randint(1, 365, (10_000, 23))) people = 23
import math r_func = list(range(10**7)) # lets just check a ton of numbers lol for i in r_func: if i == int(sum([math.factorial(int(k)) for k in str(i)])): print(i)
n = int(input()) time = [] mod = 1000000007 from collections import Counter from math import factorial for _ in range(n): t = int(input()) time.append(t) c = Counter(time) ans = 1 for v in list(c.values()): ans *= factorial(v) ans %= mod t = 0 time.sort() for i in range(1, n): time[i] += time[i - 1] for j in range(n): t += time[j] print(t) print(ans)
import math # Questão 1 count = 0 for i in range(1, 5000001, 1): if i % 49 == 0 and i % 37 == 0 and i % 2 == 0: count += 1 print(count) # Questão 2 x = [] for i in range(10): if i % 2 == 0: X = 3**i + 7 * (math.factorial(i)) else: X = 2**i + 4 * math.log(i) x.append(X) num = 0 soma = 0 posicao = 0 count = 0 for a in x: soma += a if a > num: num = a posicao = count count += 1 media = soma / 10 print('o maior número está na posição {0}'.format(posicao)) print('a média é {0:.2f}'.format(media))
def n_choose(self, n, k): n_choose = (math.factorial(n)) / (math.factorial(k) * math.factorial(n - k)) return n_choose
# Project Euler - Question 15 # Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, how many routes # are there to the bottotm right corner through a 20x20 grid? import time from math import factorial n = 20 ans = factorial(2*n)/(factorial(n)**2) print(int(ans)) print('Time Elapsed:', time.perf_counter(), 'seconds')
def combinations_count(n, r): return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))
def factorial(num): print(math.factorial(num))
def lattice_paths(n): "Returns the total number of possible paths in an n-by-n grid from one corner to the opposite corner." routes = (math.factorial(2*n)/pow(math.factorial(n),2)) return int(routes)
# 1 <= N <= 10**5 import math N = int(input()) ans = math.factorial(N) # for i in range(1, N+1): # ans = ans*i print(ans % (10**9 + 7))
def fact(request, n): n = int(n) return HttpResponse("<h2>factorial is {}</h2>".format(factorial(n)))
def gridMovingCountByBinomial(x, y): # use explict // for true division, otherwise, a estimation will be given for classic division / return math.factorial(x + y) // (math.factorial(x) * math.factorial(y))
import math print(math.ceil(3.90)) # This will return 4 print(math.floor(3.90)) # This will print 3 print(math.factorial(5)) # Print factorial of 5 ie- 120 print(math.gcd(36, 92)) # This will print greatest common divisor of two nos print(math.sqrt(64)) # This will result the square root of the function
def fact(x, y): return math.factorial(x)
import math n = int(input()) if n % 2 == 1: print(0) else: print((math.factorial(n) // math.factorial(n // 2)**2) // (n // 2 + 1))
alp.append(chr(ord('A') + i)) print(alp) print("------------------------") a = [[1, 3], [2, 6], [15, 18], [8, 10], [3, 10]] a.sort() print(a) import bisect b = [2, 4] bisect.insort(a, b) print(a) print("------------------------") b = [[5, 8], [9, 11], [12, 15], [15, 22]] n = [1, 13] l = len(b) x = bisect.bisect(b, n) if (b[x - 1] > n) and (n < b[x]): bisect.insort(b, n) print(b) print("------------------------") import math print(math.factorial(200)) print("------------------------") print(1 / 2)
def get_r(x, n): return get_der(x + 1, n + 1) * (x ** (n + 1)) / math.factorial(n + 1)
import math n = eval(input('Introduceti n: ')) s = 0 for i in range(1, n + 1): s += math.factorial(i) print('Suma = ', s)
def combination(n, k): return int( (math.factorial(n)) / ((math.factorial(k)) * (math.factorial(n - k))))
def get_der(x, n): if n == 0: return np.log(x) else: return ((-1) ** (n + 1)) * 1.0 * math.factorial(n - 1) / (x ** n)
def _factorial(num): # sleep 2 seconds because it takes very less time # so that you can see the actual difference time.sleep(2) print(math.factorial(num))
import math n = int(input("Kitne line chahiye bhiaya ")) for i in range(0, n + 1): print(" " * (n - i), end="") for j in range(0, i + 1): print(int( math.factorial(i) / (math.factorial(i - j) * math.factorial(j))), end=" 15") if j == i: print()
def permutation_formula(n, r): return factorial(n) // factorial(n-r)
def savitzky_golay(y, window_size, order, deriv=0, rate=1, returnScoreList=False): ''' Smooths over data using a Savitzky Golay filter This can either return a list of scores, or a list of peaks y : array-like, score list window_size : int, how big of a window to smooth order : what order polynomial returnScoreList : bool ''' from math import factorial y = np.array(y) try: window_size = np.abs(np.int(window_size)) order = np.abs(np.int(order)) except ValueError: raise ValueError("window_size and order have to be of type int") if window_size % 2 != 1 or window_size < 1: raise TypeError("window_size size must be a positive odd number") if window_size < order + 2: raise TypeError("window_size is too small for the polynomials order") order_range = range(order + 1) half = (window_size - 1) // 2 # precompute coefficients b = np.mat([[k**i for i in order_range] for k in range(-half, half + 1)]) m = np.linalg.pinv(b).A[deriv] * rate**deriv * factorial(deriv) # pad the signal at the extremes with values taken from the signal itself firstvals = y[0] - np.abs(y[1:half + 1][::-1] - y[0]) lastvals = y[-1] + np.abs(y[-half - 1:-1][::-1] - y[-1]) y = np.concatenate((firstvals, y, lastvals)) filtered = np.convolve(m[::-1], y, mode='valid') if returnScoreList: return np.convolve(m[::-1], y, mode='valid') # set everything between 1 and -inf to 1 posFiltered = [] for i in range(len(filtered)): if 1 > filtered[i] >= -np.inf: posFiltered.append(1) else: posFiltered.append(filtered[i]) # use slopes to determine peaks peaks = [] slopes = np.diff(posFiltered) la = 45 # how far in sequence to look ahead for i in range(len(slopes) - 50): if i > len(slopes) - la: # probably irrelevant now dec = all(slopes[i + x] < 0 for x in range(1, 50)) if slopes[i] > 0 and dec: if i not in peaks: peaks.append(i) else: dec = all(slopes[i + x] < 0 for x in range(1, la)) if slopes[i] > 0 and dec: peaks.append(i) return peaks
import math a, b = map(int, input().split()) print(int(math.factorial(a) / (math.factorial(b) * math.factorial(a - b))))
def combination_formula(n, r): return factorial(n) // (factorial(r)*factorial(n-r))
# Project Euler --> https://projecteuler.net/problem=24 # Problem 24 : Lexicographic permutations from math import factorial digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] result = [] index = 999999 for j in range(9, -1, -1): n = int(index / factorial(j)) result.append(str(digits[n])) index -= n * factorial(j) del digits[n] print(''.join(result))
import math n = int(input("Enter the value of n in Euler's formula: ")) sum1 = 1 for i in range(1, n + 1): sum1 = sum1 + (1 / math.factorial(i)) print("value of e is :", round(sum1, 2)) #Lucciffer