How to Solve the Famous Rabbit and Chicken Problem in Python


With this example, we will see how to resolve the Famous Rabbit and Chicken Problem in Python i.e.

Solution

The number of a rabbit’s feet is double of a chicken’s feet. Based on the total number of feet given above, the numbers of rabbits and chickens are calculated to be (m / 2-n) and (2 * n – m / 2) respectively.

Note: We need to test that the number of chicken and rabbits is greater than or equal to 0. And the total number of feet for chicken or rabbits should be even.

Source Code

while True:
    try:
        sum = eval(input("Please enter total number of chicken and rabbit feet: "))
        head = eval(input("Please enter total number of chicken and rabbits: "))

        if sum < 6: print("Please re-enter total number of feet>>>")
        elif head < 2: print("Please re-enter total number of chicken and rabbits>>>")
        else:
            j = 0
            t = 0
            flag = True
            while j < head and flag==True:
                j += 1
                t = head - j
                if (sum == (j * 2 + t * 4)):
                    print("The number of Chicken and Rabbits are %d and %d respectively" % (j, t))
    except:
        print("program error")

Output

Please enter total number of chicken and rabbit feet: 32
Please enter total number of chicken and rabbits: 14
The number of Chicken and Rabbits are 12 and 2 respectively
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments