美文网首页从零开始学Python
百钱买百鸡的Python实现

百钱买百鸡的Python实现

作者: iLester | 来源:发表于2018-02-09 11:46 被阅读19次

    “百钱买百鸡”是一个很有历史的问题了,大意就是:小鸡半文一只,母鸡一文一只,公鸡二文一只,现有一百文钱,刚好买了一百只鸡,请问小鸡、母鸡与公鸡各有多少只?

    如果假设小鸡、母鸡和公鸡各有a,b,c,那么同时满足以下两个条件的均可以符合题意:
    a + b +c =100
    0.5a + 1b + 2*c = 100

    显然不止一组解,可以用Python进行穷举,代码如下:

    for i in range(1, 101):
        for j in range(1, 101-i):
            for m in range(1, 101-i -j):
                if i * 0.5+j*1 + m *2 == 100 and i + j + m == 100:
                    print('chicken(s):{}, hen(s):{}, rooster(s):{}.'.format(i, j, m))
    

    测试运行的结果是:

    chicken(s):2, hen(s):97, rooster(s):1.
    chicken(s):4, hen(s):94, rooster(s):2.
    chicken(s):6, hen(s):91, rooster(s):3.
    chicken(s):8, hen(s):88, rooster(s):4.
    chicken(s):10, hen(s):85, rooster(s):5.
    chicken(s):12, hen(s):82, rooster(s):6.
    chicken(s):14, hen(s):79, rooster(s):7.
    chicken(s):16, hen(s):76, rooster(s):8.
    chicken(s):18, hen(s):73, rooster(s):9.
    chicken(s):20, hen(s):70, rooster(s):10.
    chicken(s):22, hen(s):67, rooster(s):11.
    chicken(s):24, hen(s):64, rooster(s):12.
    chicken(s):26, hen(s):61, rooster(s):13.
    chicken(s):28, hen(s):58, rooster(s):14.
    chicken(s):30, hen(s):55, rooster(s):15.
    chicken(s):32, hen(s):52, rooster(s):16.
    chicken(s):34, hen(s):49, rooster(s):17.
    chicken(s):36, hen(s):46, rooster(s):18.
    chicken(s):38, hen(s):43, rooster(s):19.
    chicken(s):40, hen(s):40, rooster(s):20.
    chicken(s):42, hen(s):37, rooster(s):21.
    chicken(s):44, hen(s):34, rooster(s):22.
    chicken(s):46, hen(s):31, rooster(s):23.
    chicken(s):48, hen(s):28, rooster(s):24.
    chicken(s):50, hen(s):25, rooster(s):25.
    chicken(s):52, hen(s):22, rooster(s):26.
    chicken(s):54, hen(s):19, rooster(s):27.
    chicken(s):56, hen(s):16, rooster(s):28.
    chicken(s):58, hen(s):13, rooster(s):29.
    chicken(s):60, hen(s):10, rooster(s):30.
    chicken(s):62, hen(s):7, rooster(s):31.
    chicken(s):64, hen(s):4, rooster(s):32.
    chicken(s):66, hen(s):1, rooster(s):33.
    

    总的来说,这是一个中小学生都适宜的好问题情境,对于小学生可以用来培养数学思维,比如小鸡不可能是单数,比如小鸡与公鸡的平均价格应该是一文一只。而对于中学生而言则可以用来锻炼程序思维。

    相关文章

      网友评论

        本文标题:百钱买百鸡的Python实现

        本文链接:https://www.haomeiwen.com/subject/zkeftftx.html