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.
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.
This challenge teaches weighted arithmetic calculations where different categories contribute different weights to a final total.
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)
chickens * 2 legs.cows * 4 legs.pigs * 4 legs.animals(cows, chickens, pigs)) applies wrong leg multipliers to animals! Keep parameter order consistent.Map parameter weights carefully. Next, let's check if a number is even or odd!
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.
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.
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.