当前位置:   article > 正文

龟兔赛跑的代码_python龟兔赛跑编程

python龟兔赛跑编程

写一个龟免赛跑的程序,要求有Animal类、

Rabbit类、Tortoise类,其中Animal类有run方法,

也有时间分配spendruntime属性,默认为1,

position属性 (当前的位置)。Rabbit设置

spendruntime的值为0.2,表示免子在跑的过程中

会停等80%的时问,重写run方法,在跑的时候用

到了每次移动10步,Tortoise类重写run方法,每

次移动3步,然后创建race函数,兔子对象每跑2

次次需要等8次,乌龟对象每次都在跑,谁的

position的值最先到达1000结束

class Animal(object):

    

    def __init__(self, name, position,spendruntime):

        self.name = name

        self.position = position

        self.spendruntime=1

        

 

    def run(self):

        print(self.name + '正在跑')

class Tortoise(Animal):

    count = 0

    def run(self, position, spendruntime):

        step = 3

        for i in range(1, 500):

            position += step

            self.count += 1

            if(position >= 1000):

                break

 

        print(f"{self.name}到达终点共用了{self.count}次数")

class Rabbit(Animal):

    count = 0

    def run(self, position,spendruntime):

        step = 10

        for i in range(1, 500):

            if((i % 10) == 1):

                position += step

            elif((i % 10) == 2):

                position += step

            self.count += 1

            if(position >= 1000):

                break

     

        print(f"{self.name}到达终点共用了{self.count}次数") #在print语句中加入f就可以起到和format函数类似的作用

def race():

    rabbit = Rabbit('兔子', 0, 0.2)

    tortoise = Tortoise('乌龟', 0, 1)

    rabbit.run(0, 0.2)

    tortoise.run(0, 1)

    if rabbit.count>tortoise.count:

        print("乌龟赢了")

    elif rabbit.count<tortoise.count:

        print("兔子赢了")

 

race()

 

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/64423
推荐阅读
相关标签
  

闽ICP备14008679号