def simulate2(): n = 10000 win1 = 0 win2 = 0 win3 = 0 win4 = 0 win5 = 0 for i in range(n): #simulate 10000 games #simulate game whose total number is 10, and player1 and player3 won 1 result = Bookie2(10, 1, 0, 1, 0, 0) if result == 1: win1 += 1 elif result == 2: win2 += 1 elif result == 3: win3 += 1 elif result == 4: win4 += 1 elif result == 5: win5 += 1 log('player1 wins: ' + str(float(win1) / float(n))) log('player2 wins: ' + str(float(win2) / float(n))) log('player3 wins: ' + str(float(win3) / float(n))) log('player4 wins: ' + str(float(win4) / float(n))) log('player5 wins: ' + str(float(win5) / float(n)))
def solve(self): sum1=43+21+35+0.0 p1=1.0/3.0 p3=21.0/sum1 dis = p1-p3 dis = round(dis,2) result = [98,dis,0] log(result) return result
def solve(self): n=51 n=math.sqrt(n) s=4.9 z1=1.1/(s/n) z1=round(z1,2) z2=1.96 log([z1,z2]) return [0.95,z1,1]
def first_year(): X=sta.norm(loc=950, scale=20)#generate random data in normal distribution whose expectation is 950 and standard deviation is 20 wbread=[] for i in range(365): x=X.rvs(size=100) wbread.append(x[0])#get the random data for one day log(numpy.mean(wbread))#print mean value log(sta.skew(wbread))#print skew value plt.hist(wbread,color='grey') plt.savefig('first_year.png')
def second_year(): X=sta.norm(loc=950, scale=20)#generate random data in normal distribution whose expectation is 950 and standard deviation is 20 wbread=[] for i in range(365): x=X.rvs(size=100) wbread.append(max(x))#get the random data for one day log(numpy.mean(wbread))#print mean value log(sta.skew(wbread))#print skew value plt.hist(wbread,color='grey') plt.savefig('second_year.png')
def solve(self): u=5.0 x=4.6 s=2.2 n=20 n=math.sqrt(n) z=(x-u)/(s/n) z=round(z,2) result=[19.0,z,1] log(result) return result
def simulate1(): n = 10000 win1 = 0 win2 = 0 for i in range(n): #simulate 10000 games #simulate game whose total number is 10, and player1 won 5, player2 won 2 result = Bookie1(10, 5, 2) if result == 1: win1 += 1 elif result == 2: win2 += 1 log('player1 wins: ' + str(float(win1) / float(n))) log('player2 wins: ' + str(float(win2) / float(n)))
def linregress1(): x = np.linspace(-5, 5, num=150) y = x + np.random.normal(size=x.size) y[12:14] += 10 slope, intercept, r_value, p_value, std_err = stats.linregress(x,y) log(slope) log(intercept) log(r_value) log(p_value) log(std_err) plt.plot(x, y, 'b.') plt.plot(x, slope * x + intercept, 'r-') plt.savefig('linregress1.png')
def nc_of_expon(): #1st non-center moment of expon distribution whose lambda is 0.5 E1 = lambda x: x*0.5*np.exp(-x/2) #2nd non-center moment of expon distribution whose lambda is 0.5 E2 = lambda x: x**2*0.5*np.exp(-x/2) log(integrate.quad(E1, 0, np.inf)) log(integrate.quad(E2, 0, np.inf)) log(expon(scale=2).moment(1)) log(expon(scale=2).moment(2))
def ttest(): x = stats.norm.rvs(loc=5, scale=10, size=50) log(stats.ttest_1samp(x,5.0)) log(stats.ttest_1samp(x,1.0))
class Solution(): def solve(self, A): result = {} for str in A: result[str] = result.get(str, 0) + 1 return result ''' 已知列表fruits中顺序保存了某商店每日出售的水果品名,例如fruits=['apple','banana','cherry','pineapple','banana','peach','pear','peach','cherry' ],完成函数solve()计算每一种水果的出售次数,存入字典result中并将结果返回 Input / Output Input Example ['apple', 'banana', 'cherry', 'pineapple', 'banana', 'peach', 'pear','peach', 'cherry' ] Input Description 一个纪录了水果出售纪录的列表 Output Example {'pear':1, 'banana':2, 'cherry':2, 'peach':2, 'pineapple':1, 'apple':1} Output Description 水果出售次数统计结果 ''' log(Solution().solve(['apple', 'banana', 'cherry', 'pineapple', 'banana', 'peach', 'pear', 'peach', 'cherry']))
#-*- coding:utf-8 -*- ''' log api example: log('output is: ' + str(output)) ''' import random from log_api import log ''' You can delete the MontyCarlo and write your Monty Carlo ''' #this function may spend a little time to execute def MontyCarlo(): n = 1000000 k = 0 for i in range(n): x = random.uniform(-1, 1) y = random.uniform(-1, 1) if x**2 + y**2 < 1: k = k + 1 return 4 * float(k) / float(n) if __name__ == '__main__': pi = MontyCarlo() #print out the result log(pi)
from log_api import log class Solution(): def solve(self, A): return np.poly1d(A) * np.poly1d(np.array([2.0, 0.0, -1.0, 1.0])) ''' 在Numpy中,多项式函数的系数可以用一维数组表示,例如对于f(x)=2x^3-x+1可表示为f=np.array([2.0,0.0,-1.0,1.0]),而np.poly1d()方法可以将多项式转换为poly1d(一元多项式)对象,返回多项式函数的值,请利用poly1d()方法计算多项式g(x)(例如g(x)=x^2+2x+1)和f(x)的乘积并将结果返回 Input / Output Input Example np.array([1.0, 2.0, 1.0]) Input Description 多项式g(x)的一维数组表示 Output Example np.poly1d([2.0,4.0,1.0,-1.0,1.0,1.0]) Output Description f(x)*g(x)的poly1d对象 ''' log(Solution().solve(np.array([1.0, 2.0, 1.0])))
# judge whether x is prime or not def prime(self, x): for i in range(2, int(x ** 0.5) + 1): if x % i == 0: return False return True ''' 完成函数solve,判断传入的整数列表A中的数字是否是素数,并将所有的素数保存到另一个列表中并返回 Input / Output Input Example [23,45,76,67,17] Input Description 一个含素数和非素数的多个整数列表 Output Example [23,67,17] Output Description 素数组成的列表 ''' log(Solution().solve([23, 45, 76, 67, 17]))
import random from log_api import log ''' You can delete the MontyCarlo and write your Monty Carlo ''' #this function may spend a little time to execute def MontyCarlo(): n = 1000000 k = 0 for i in range(n): x = random.uniform(-1, 1) y = random.uniform(-1, 1) if x**2 + y**2 < 1: k = k + 1 return 4 * float(k) / float(n) if __name__ == '__main__': pi = MontyCarlo() #print out the result log(pi)
#not hit at the first and change the mind else: return 1 if __name__ == '__main__': #repeat 10000 times n = 10000 #not sure whether to change the mind win = 0 for i in range(n): Dselect = random.randint(1, 3) Dchange = random.randint(0, 1) win = win + MontyHall(Dselect, Dchange) log(float(win) / float(n)) #be sure not to change the mind win = 0 for i in range(n): Dselect = random.randint(1, 3) Dchange = 0 win = win + MontyHall(Dselect, Dchange) log(float(win) / float(n)) #be sure to change the mind win = 0 for i in range(n): Dselect = random.randint(1, 3) Dchange = 1 win = win + MontyHall(Dselect, Dchange)
def nc_of_norm(): f1 = lambda x: x**4 f2 = lambda x: x**2-x+2 log(norm.expect(f1, loc=1, scale=2)) log(norm.expect(f2, loc=2, scale=5))
for str in A: if self.isPalindrome(str): result.append(str) return result def isPalindrome(self, x): return x == x[::-1] ''' 对于一个包含一系列数字字符串的列表,寻找其中的回文串存入一个列表中并返回 Input / Output Input Example ['123', '232', '4556554', '12123', '3443','1314131'] Input Description 一个包含一系列数字字符串的列表 Output Example ['232', '4556554', '3443','1314131'] Output Description 仅包含回文串的列表 ''' log(Solution().solve(['123', '232', '4556554', '12123', '3443', '1314131']))
def oneway_anova(): A1=[27.0, 26.2, 28.8, 33.5, 28.8] A2=[22.8, 23.1, 27.7, 27.6, 24.0] A3=[21.9, 23.4, 20.1, 27.8, 19.3] A4=[23.5, 19.6, 23.7, 20.8, 23.9] A=[A1, A2, A3, A4] n=20 As=np.sum(A, axis=1) QA=0.0 for i in range(4): QA=QA+As[i]*As[i] QA=QA/5 QT=0.0 for i in range(4): for j in range(5): QT=QT+A[i][j]*A[i][j] C=np.sum(A)*np.sum(A)/n ST=QT-C SA=QA-C Se=ST-SA F=(SA/3)/(Se/16) log('QA is ' + str(QA)) log('QT is ' + str(QT)) log('C is ' + str(C)) log('ST is ' + str(ST)) log('SA is ' + str(SA)) log('Se is ' + str(Se)) log('F is '+ str(F))
def chisquare(): A=[16, 18, 16, 14, 12, 12] B=[16, 16, 16, 16, 16, 8] log(stats.chisquare(A)) log(stats.chisquare(A, f_exp=B))
# -*- coding:utf-8 -*- ''' log api example: log('output is: ' + str(output)) ''' import numpy as np from log_api import log class Solution(): def solve(self): # 1 - P(X = 0) >= 0.98 # 1 - e^(-lambda) >= 0.98 # lambda >= -ln(0.02) l = -np.log(0.02) return np.ceil(l) ''' 假定一块蛋糕上的葡萄干粒数服从泊松分布,如果想让每块蛋糕上至少有一粒葡萄干的概率大于等于0.98,蛋糕上葡萄干的平均粒数应该是多少? Output Example 1 Output Description num_of_grape, int类型数字 ''' log(Solution().solve())
def nc_of_uniform(): rv = uniform(loc=2, scale=6) log(rv.mean()) log(rv.var()) log(rv.moment(1)) log(rv.moment(2)) log(rv.moment(3)) log(rv.moment(4)) log(rv.stats(moments='mvsk'))
def nc_of_poisson(): rv = poisson(mu=5) log(rv.mean()) log(rv.var()) log(rv.moment(1)) log(rv.moment(2)) log(rv.moment(3)) log(rv.moment(4)) log(rv.stats(moments='mvsk'))
def estimate(): number_experiments = 10000 upper_bound = 100 H1 = H2 = H3 = MSE1 = MSE2 = MSE3 = ME1 = ME2 = ME3 = 0.0 for j in range(number_experiments): N = number_trans(upper_bound) evidence = train_seen(N) hypo1 = MLE_estimation(evidence) hypo2 = MSE_estimation(evidence) hypo3 = ME_estimation(evidence) #calculating hits H1 = H1 + 1 if hypo1==N else H1 H2 = H2 + 1 if hypo2==N else H2 H3 = H3 + 1 if hypo3==N else H3 #calculating mean squared error MSE1 = MSE1 + (hypo1-N)**2 MSE2 = MSE2 + (hypo2-N)**2 MSE3 = MSE3 + (hypo3-N)**2 #calculating mean error ME1 = ME1 + (hypo1-N) ME2 = ME2 + (hypo2-N) ME3 = ME3 + (hypo3-N) log(H1/number_experiments) log(H2/number_experiments) log(H3/number_experiments) log(MSE1/number_experiments) log(MSE2/number_experiments) log(MSE3/number_experiments) log(ME1/number_experiments) log(ME2/number_experiments) log(ME3/number_experiments)
x_delta = [xi - x_mean for xi in x] y_delta = [yi - y_mean for yi in y] sum_xy = np.sum([x_delta[i] * y_delta[i] for i in range(0, n)]) sum_x2 = np.sum([xd**2 for xd in x_delta]) sum_y2 = np.sum([yd**2 for yd in y_delta]) r_val = sum_xy / np.sqrt(sum_x2) / np.sqrt(sum_y2) if abs(r_val) == 1.0: p_val = 0.0 else: t2 = r_val**2 * ((n - 2) / ((1.0 - r_val) * (1.0 + r_val))) p_val = 1 - beta.sf((n - 2) / (n - 2 + t2), 0.5 * (n - 2), 0.5) return [round(r_val, 6), round(p_val, 6)] ''' 利用python实现简化版皮尔森相关系数计算函数 注意事项: 1)scipy包只能使用scipy.x.ppf或scipy.x.sf函数 2)x,y为空时,返回值为[None,None] 3)结果保留6位小数点 Input Description x : 一维数组;y : 一维数组,且x、y长度相同 Output Description [r-val,p-value]分别代表皮尔森相关系数、检验结果P值 ''' log(Solution().solve([1, 2, 3], [2, 2, 3]))
def nc_of_binom(): rv = binom(10,0.2) log(rv.mean()) log(rv.var()) log(rv.moment(1)) log(rv.moment(2)) log(rv.moment(3)) log(rv.moment(4)) log(rv.stats(moments='mvsk'))
result[i] = 0 for str in A: for c in str: i = int(c) result[i] += 1 return result ''' 已知有一个由数字字符串构成的列表,统计列表中数字字符'0'-'9'各自出现的次数并返回统计结果 Input / Output Input Example ['12','34','567', '36','809','120'] Input Description 一个由数字字符串构成的列表 Output Example {0:2, 1:2, 2:2, 3:2, 4:1, 5:1, 6:2, 7:1, 8:1, 9:1} Output Description 各数字字符的出现次数 ''' log(Solution().solve(['12', '34', '567', '36', '809', '120']))
def ttest(): x = stats.norm.rvs(loc=5, scale=1, size=50) y = stats.norm.rvs(loc=2, scale=10, size=50) log(stats.ttest_ind(x, y)) log(stats.ttest_ind(x, y, equal_var = False))