Loop_The problem of chicken and rabbit

The problem of chicken and rabbit is a classical problem in mathematics. How do we solve this problem with python? Here is my code.

def calculate(head_number, leg_number,):
    #To judge whether the number of leg and head is correct
    if (head_number > 2*leg_number) or (leg_number > 4*head_number):
        print ("You made a mistake. Re enter the number please:")
        head_number = int(input("The number of head is:"))
        leg_number = int(input("The number of leg is:"))
    total_number = int(head_number)

    #i is the number of chickens, j is the number of rabbits; calculate the number of them
    for i in range(0,total_number+1):
        for j in range(0,total_number+1):
            if (i+j == head_number) and (2*i+4*j == leg_number):
                print ("The number of pig is: ",i)
                print ("The number of rabbit is: ",j)

Tips
The general way of solving this problem is to use system of linear equations of two unknowns. But as for the practical application, there are two different mode between computer and human.
While human deal with this problem, they will use elimination to get the answer of system of linear equations of two unknowns. The process of thinking contains intelligence. As for computers, their way is relatively rigid. Computers use Exhaustive Attack method to get the correct answer. It is "rude" but relatively effective because of computing power of computers.

Actually we can use a more effective way to solve this problem, dichotomy.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,162评论 0 10
  • NO.7 SIX的演唱会(1) 一觉睡到大天亮,貌似又要旷一次课了。 昨天发生的事像是梦一样,在殷怜安短短19年的...
    初琰阅读 1,826评论 0 0
  • spark social media urpoar drag screaming from his seat du...
    c花海阅读 643评论 0 0
  • 什么是CocoaPods CocoaPods是Xcode上的依赖管理工具。官网:https://cocoapods...
    iOSnow阅读 4,082评论 0 1