一直有在学,不过没来博客园,随便写点吧,写个阶乘的小代码
def f(n): last=1 for i in range(1,n+1): last*=i return last num=int(input(‘what the number\n‘)) print(‘f‘+‘(‘+str(num)+‘)=‘,f(num))
或者用递归的思路
def fact(n): if n==1: return 1 return n*fact(n-1) num=int(input(‘what the number\n‘)) print(‘fact‘+‘(‘+str(num)+‘)=‘,fact(num))
下面是三种思路的斐波数列:
1:
def fibo(n): befor=0 after=1 for i in range(n-2): ret=after+befor befor=after after=ret return ret print(fibo(7))
2:
def fibo(n): if n==1: return 0 elif n==2: return 1 return fibo(n-1)+fibo(n-2) print(fibo(7))
3:
def fibo(n): if n<=2: return n-1 return fibo(n-1)+fibo(n-2) print(fibo(7))
时间: 2024-10-14 14:20:09