标签:code += elf pretty pytho font color tty python3
10):古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?
程序分析:兔子的规律为数列1,1,2,3,5,8,13,21....
程序源代码:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
f1 = 1
f2 = 1
for i in range(1,22):
print ‘%12ld %12ld‘ % (f1,f2),
if (i % 3) == 0:
print ‘‘
f1 = f1 + f2
f2 = f1 + f2
以上实例输出结果为:
1 1 2 3 5 8
13 21 34 55 89 144
233 377 610 987 1597 2584
4181 6765 10946 17711 28657 46368
75025 121393 196418 317811 514229 832040
1346269 2178309 3524578 5702887 9227465 14930352
24157817 39088169 63245986 102334155 165580141 267914296
#!/usr/bin/python
# -*- coding: UTF-8 -*-#
#递归做,非常慢。计算n=36就要大概七八秒吧
def fib(n):
if n==1 or n==2:
return 1
else:
return fib(n-1)+fib(n-2)
print fib(36)
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# time 为第几个月,n 为 3
def rabbit(time,n):
if time<1:
return 0
elif time==1:
num=1
elif time<n:
num=1
else:
num=rabbit(time-1,n)+rabbit(time-(n-1),n)
return num
print rabbit(25,3)
#!/usr/bin/python
# -*- coding: UTF-8 -*-
def rabbit(num):
f1 = 1
#第一个月为1
f2 = 1
#第二个月为1
if num == 1 or num == 2:
return 1
else:
for i in xrange(num-1):
f1,f2 = f2,f1+f2
return f1
# 第三十六月兔子数量
print rabbit(36)
使用斐波那契数列:
# !/usr/bin/python
# coding=UTF-8
n = int(raw_input("第几个月: "))
# 斐波那契数列的通项公式
f =(1/(5**0.5))*(((1+(5**0.5))/2)**n - ((1-(5**0.5))/2)**n)
print "第%d个月:共%d只" % ( n,f)
Python3 参考方法:
#!/usr/bin/python3
def rabbit(n):
count = [1,0,0] #将兔子成长期分为三个月
for i in range(1,n): #每个月更新一次不同成长期的兔子对数
count[2] = count[2] + count[1]
count[1] = count[0]
count[0] = count[2]
return count[0]+count[1]+count[2] #返回兔子对数总数
n = int(input("查看第几个月的兔子对数:"))
rabbit_sum = rabbit(n)
print("第%d个月的兔子对数为%d"%(n,rabbit_sum))
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
def Rabbit(num):
i = 1
a,b = 1,1
while i <= num:
yield a
i += 1
a,b = b,a+b
list = [x for x in Rabbit(20)]
print(list)
# -*- coding: utf-8 -*-
Rabbits={‘rabbits‘:0} # 新生兔子
home=[{‘rabbits‘:1}] # 所有兔子对都在这个列表中,初始按过完一月计算
month=int(raw_input(‘请输入月份:‘))
time=1 # time 表示已经过完的月数,到了该月月末。
while time <month:
for j in home:
if j[‘rabbits‘]>=2:
home.append(Rabbits.copy())
else:
j[‘rabbits‘]+=1
time+=1
print ‘兔子数量为 %u。‘% len(home)
#!/usr/bin/python
# -*- coding: UTF-8 -*-
a = 1
b = 1
for i in range(1,21,2):
print ‘%d %d‘%(a,b),
a += b
b += a
# -*- coding: UTF-8 -*-
def rabbit(n):
if n == 1:
return [1]
if n == 2:
return [1,1]
rabbits = [1,1]
for i in range(2,n):
rabbits.append( rabbits [-1] + rabbits [-2]) #取List倒数第一个和倒数第二个数值相加
return rabbits
print rabbit(18) #第十八个月的数量
all_rabbit = []
class Rabbit():
def __init__(self, birthday):
self.birthday = birthday
all_rabbit.append(self)
def makechild(self, month):
if month-self.birthday>=2:
Rabbit(month)
Rabbit(1)
for i in range(1, 22):
[j.makechild(i) for j in all_rabbit[:]]
print(len(all_rabbit))
简单的练习小例子,有兴趣的可以来试试。如果感觉不错的话,请多多点赞支持哦。。。
原文链接:https://blog.csdn.net/luyaran/article/details/80046801
标签:code += elf pretty pytho font color tty python3
原文地址:https://www.cnblogs.com/luyaran/p/8942095.html