• 一个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()
  • 相关阅读:
    使用 Eclipse 平台共享代码
    给定一个整数数组,其中元素的取值范围为0到10000,求其中出现次数最多的数
    学习
    eclipse优化
    约瑟夫环
    propedit插件
    OData 11 入门:实现一个简单的OData服务
    OData 14 OData语法(上)
    CLR via C# 读书笔记 54 在使用非托管资源情况下的GC
    面试:等车时间
  • 原文地址:https://www.cnblogs.com/jianc/p/11722940.html
Copyright © 2020-2023  润新知