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.

你可能感兴趣的:(Loop_The problem of chicken and rabbit)