Given that headcount and the leg count you have to write a Python program to find the number of chickens and the number of rabbits in a Farm.
As we all know rabbit and chicken have only one head but when it comes to the legs rabbits have four legs and chicken have two legs.
Write a python program to solve a classic ancient Chinese puzzle. We count 35 heads and 94 legs among the chickens and rabbits in a farm. How many rabbits and how many chickens do we have?
Let take two variables headcount and legs count and initialize it to 35 and 94 respectively
head_count = 35
leg_count = 94
leg_count = 94
Given the count of head and legs, let's try to find the number of four legged animals that are trying to find the rabbit count in the farm.
Let's assume rabbits have two heads and multiply heads by 2, and subtract the product by total legs then divide it by 2 you will get the total number of rabbits in the farm.
rabbits = (leg_count - (2 * head_count)) / 2
Once we find the number of rabbits. Subtract total heads by the rabbit headcount this will give us the total number of chickens present in the farm.
chickens = head_count - rabbits
After finding the number of rabbits and number of seconds use the print function to print the count of chickens and rabbits
print("Number of Rabbits in farm are : " + str(rabbits))
print("Number of Chickens in farm are : " + str(chickens))
Final program
=======================
head_count = 35
leg_count = 94
rabbits = (leg_count - (2 * head_count)) / 2
chickens = head_count - rabbits
print("Number of Rabbits in farm are : " + str(rabbits))
print("Number of Chickens in farm are : " + str(chickens))
OUTPUT:
========================
Number of Rabbits in farm are : 12.0
Number of Chickens in farm are : 23.0
The above python program can also be written by asking a user to enter the head count and the legs count using input function call.
Check if legs count and head count are not equal to zero using if statement and also headcount should be less than the legs count
total_heads = int(input("Enter number of heads :"))
total_legs = int(input("Enter number of legs :"))
if total_legs < total_heads or total_legs == 0 or total_heads == 0 or total_legs % 2 != 0:
print("Invalid input !")
else:
rabbits = (total_legs - (2 * total_heads)) / 2
chickens = total_heads - rabbits
print("Number of Rabbits in farm are : " + str(rabbits))
print("Number of Chickens in farm are : " + str(chickens))
Use the same logic to get the four legged animal that is rabbit first by multiplying headcount by to and subtracting in the legs and dividing by 2.
After finding four-legged animal count subtract it by total headcount number of two legged animal count
OUTPUT
===============
Enter number of heads :35
Enter number of legs :94
Number of Rabbits in farm are : 12.0
Number of Chickens in farm are : 23.0
Conclusion: Try to run the program by yourself comment down below if any suggestion
0 Comments