Coding Challenge < Python >

Write a 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?
Solution:
def solve(numheads,numlegs): ns='No solutions!' for i in range(numheads+1): j=numheads-i if 2i+4j==numlegs:...
Jump to solution
2 Replies
Solution
Camila_99$$
Camila_99$$9mo ago
def solve(numheads,numlegs): ns='No solutions!' for i in range(numheads+1): j=numheads-i if 2i+4j==numlegs: return i,j return ns,ns numheads=35 numlegs=94 solutions=solve(numheads,numlegs) print solutions
Manuel
Manuel9mo ago
heads = 35
legs = 94
headsPerChicken = 1
headsPerRabbit = 1
legsPerChicken = 2
legsPerRabbit = 4

import numpy as np
equations = np.array([[headsPerChicken, headsPerRabbit], [legsPerChicken, legsPerRabbit]])
solutions = np.array([heads, legs])
chickens, rabbits = np.linalg.solve(equations, solutions)

print(f'{rabbits:g}', "rabbits and", f'{chickens:g}', "chickens add up to", heads, "heads and", legs, "legs.")
heads = 35
legs = 94
headsPerChicken = 1
headsPerRabbit = 1
legsPerChicken = 2
legsPerRabbit = 4

import numpy as np
equations = np.array([[headsPerChicken, headsPerRabbit], [legsPerChicken, legsPerRabbit]])
solutions = np.array([heads, legs])
chickens, rabbits = np.linalg.solve(equations, solutions)

print(f'{rabbits:g}', "rabbits and", f'{chickens:g}', "chickens add up to", heads, "heads and", legs, "legs.")
Want results from more Discord servers?
Add your server