abcdef

一个python练习

问题描述:

有一对兔子,每隔3个月就生一对兔子,生下来的兔子也是每隔3个月就生兔子,以此类推。。。

用python模拟出来:

 1 #!/usr/bin/python3
 2 import random
 3 import string
 4 
 5 
 6 class APairOfRabbits():
 7     def __init__(self):
 8         self.age = 1
 9         self.malename = ''.join(random.sample(string.ascii_letters, 5))
10         self.femalename = ''.join(random.sample(string.ascii_letters, 4))
11         self.childs = []
12         self.parent = None
13     def getParentInfo(self):
14         if (None == self.parent):
15             return None
16         else:
17             print("ParentsName: %s" % self.parent.getName())
18     def getChildsInfo(self):
19         for child in self.childs:
20             print("ChildsName:%s" % child.getName())
21         print("")
22     def info(self):
23         print('%s and %s: age %d' % (self.malename, self.femalename, self.age))
24         self.getParentInfo()
25         self.getChildsInfo()
26 
27     def propagate(self):
28         self.childs.append(APairOfRabbits())
29         self.childs[-1].setParent(self)
30     def getName(self):
31         return self.malename + "-" + self.femalename
32     def growUpOfMonth(self):
33         self.age += 1
34         if(0 == (self.age % 3)):
35             self.propagate()
36 
37     def setParent(self, parent):
38         self.parent = parent
39     def getParent(self):
40         return self.parent
41     def getChilds(self):
42         return self.childs
43 
44 class RabbitsFamily():
45     def __init__(self):
46         self.rootRabbits = APairOfRabbits()
47     def dfsUpdateState(self, parent = None):
48         if None == parent:
49             parent = self.rootRabbits
50         for child in parent.getChilds():
51             self.dfsUpdateState(child)
52         parent.growUpOfMonth()
53     def dfsShowState(self, parent = None):
54         if None == parent:
55             parent = self.rootRabbits
56         parent.info()
57         for child in parent.getChilds():
58             self.dfsShowState(child)
59     
60 rabbitsFamily = RabbitsFamily()
61 for i in range(55):
62     rabbitsFamily.dfsUpdateState()
63 rabbitsFamily.dfsShowState()

 

posted @ 2019-10-22 22:01  jianc  阅读(212)  评论(0编辑  收藏  举报