The Farm Problem: Counting Animal Legs
Quick Overview
Multiplying each count by its legs and summing is `O(1)` no matter how large the herd, using arithmetic rather than iteration. Looping over individual animals does the same work n times over.
Deep Dive
1. The Challenge: Counting Legs on a Farm
A farmer asks you to count how many legs there are among all his animals. The farmer breeds three species: chickens (2 legs), cows (4 legs), and pigs (4 legs). Create a function animals(chickens, cows, pigs) that returns the total number of legs of all the animals.
2. Why It Matters
This challenge teaches weighted arithmetic calculations where different categories contribute different weights to a final total.
3. The Python Solution
Multiply each animal count by its leg multiplier and sum the results:
def animals(chickens, cows, pigs):
return (chickens * 2) + (cows * 4) + (pigs * 4)
# Testing our function
print(animals(2, 3, 5)) # Output: 36 (4 + 12 + 20)
print(animals(1, 2, 3)) # Output: 22 (2 + 8 + 12)
print(animals(5, 2, 8)) # Output: 50 (10 + 8 + 32)
4. Formula Breakdown
- Chickens contribute
chickens * 2legs. - Cows contribute
cows * 4legs. - Pigs contribute
pigs * 4legs.
5. Common Mistakes
- Mismatched Argument Order: Passing arguments in the wrong order (e.g.
animals(cows, chickens, pigs)) applies wrong leg multipliers to animals! Keep parameter order consistent.
6. Next Steps
Map parameter weights carefully. Next, let's check if a number is even or odd!
Next Up in Python Beginner Practice & Core Problem Solving
Return the Sum of Two Numbers
A function with no `return` hands back `None`, so a forgotten one surfaces as a `TypeError` at the call site rather than at the line that actually caused it.
Convert Minutes into Seconds
`minutes * 60` returns an `int` when given an `int`, while `/` always produces a float regardless of the operands. Multiplication preserves the type; division does not.
Calculate the Area of a Triangle
`base * height / 2` always yields a float in Python 3 because `/` never returns an int, even for whole numbers. `//` floors instead, which is almost never what an area wants.