defprime(p):
flag =Trueif p ==1:
flag =Falseelse:for i inrange(2,p):if p % i ==0:
flag =Falsereturn flag
defPrimeSum(m,n):
summ =0for i inrange(m,n):if prime(i):
summ += i
return summ
第6章函数-3 使用函数统计指定数字的个数 (20分)
defCountDigit(number,digit ):
str1 =str(number)
str2 =str(digit)
count =0for i in str1:if str2 == i:
count +=1return count
第6章函数-4 使用函数输出指定范围内Fibonacci数的个数 (20分)
deffib(n):
n = n +1
x1 =1
x2 =1
result =1if n <=2:passelse:for i inrange(n-2):
result = x1 + x2
x1 = x2
x2 = result
return result
defPrintFN(m,n):
list1 =[]
i =1while(fib(i)<m):
i +=1while(fib(i)<=n):
list1.append(i)
i +=1return list1
第6章函数-5 使用函数求余弦函数的近似值 (20分)
import math
deffuncos(eps,x ):
sign =1
i =0
ans =0while(abs(sign *pow(x,i)/math.factorial(i))>= eps):
ans += sign *pow(x,i)/math.factorial(i)
sign =- sign
i +=2return ans
第6章函数-6 缩写词 (20分)
defacronym(phrase):
str1 =""
list1 = phrase.split()for i in list1:
str1 += i[0].upper()return str1