1、n的阶乘
1.1、方式一:普通循环
def func(n):
s=1
for i in range(2,n+1):
s*=i
return s
1.2、方式二:普通循环
def func(n):
s=1
for i in range(n,1,-1):
s*=i
return s
1.3、方式三:递归方式
def func(n):
if n < 2:
return 1
return func(n-1) * n
2、猴子吃桃问题
2.1、需求
猴子第一天摘下若干个桃子,当即吃了一半,还不过瘾,又多吃了一个。第二天早上又将剩下的桃子吃掉一半,又多吃了一个。
以后每天早上都吃了前一天剩下的一半多一个。到第10天早上想吃时,只剩下一个桃子了。求第一天共摘多少个桃子
2.2、思路
思路:
假设猴子摘了x个桃
d1 x //2 - 1
d2 d1//2 - 1
d3 d2//2 - 1
...
d9 d8//2 - 1
d10 1
2.3、代码
2.3.1、循环方式
peach = 1
days = 9
for i in range(days):
peach = 2*(peach+1)
print(peach)
2.3.2、递归方式
# 方式一
def fn(days=9,peach=1):
peach=2*(peach+1)
if days==1:
return peach
return fn(days-1,peach)
print(fn())
# 方式二
def peach(days=10):
if days==1:
return 1
return 2*(peach(days-1)+1)
print(peach())
3、打印图形
3.1、上三角
3.1.1、需求

3.1.2、方式1:代码
def func1(n):
tail = ' '.join(map(str,range(n,0,-1)))
width = len(tail)
for i in range(1,n+1):
line = ' '.join(map(str,range(i,0,-1)))
print('{:>{}}'.format(line,width))
func1(12)
3.1.3、方式2:代码
def func1(n):
tail = ' '.join(map(str,range(n,0,-1)))
width = len(tail)
step=2
start=-1
points={10**i for i in range(1,3)}
for i in range(1,n+1):
line=tail[start:]
print('{:>{}}'.format(line,width))
if i+1 in points:
step+=1
start=start-step
func1(12)
3.2、下三角
3.2.1、需求

3.2.2、方式1:代码
def func1(n):
tail = ' '.join(map(str,range(n,0,-1)))
width = len(tail)
step=len(str(n))+1
start=0
points={10**i for i in range(1,3)}
for i in range(n,0,-1):
line=tail[start:]
print('{:>{}}'.format(line,width))
if i+1 in points:
step-=1
start=start+step
func1(12)
3.2.3、方式2:代码
def func1(n):
tail = " ".join(map(str, range(n, 0, -1)))
print(tail)
width = len(tail)
for i, c in enumerate(tail):
if c == ' ':
print("{:>{}}".format(tail[i+1:], width))
func1(12)
4、比较函数
4.1、使用内建函数
def get_values(a,b,*args):
src=(a,b,*args)
return min(src),max(src)
print(get_values(2,5,7,2,21))
4.2、使用排序函数
def get_values(a,b,*args):
m,*_,n=sorted((a,b,*args))
return m,n
get_values(5,1,3,7,7,99)
4.3、自定义排序函数
def get_values(a,b,*args):
m,n=(b,a) if a>b else (a,b)
for i in args:
if i>n:
n=i
elif i<m:
m=i
return m,n
print(get_values(5,1,3,7,7,99))
5、编写mymap函数
5.1、需求
编写一个函数,能够实现内建函数map的功能,函数签名 def mymap(func, iterable, /)
5.2、代码
def mymap(func,iterable,/):
for x in iterable:
yield func(x)
f = mymap(lambda x:x**2,range(5))
for i in f:
print(i)