March 18, 2010

Number and Age of David's Kids

Problem: The product of the ages of David's children is the square of the sum of their ages. David has less than eight children. None of his children have the same age. None of his children is more than 14 years old. All of his children is at least two years old. How many children does David have, and what are their ages?

Answer: (12,6,4,2)

Solution: show

Source Code: david_kids_ages.py

4 comments:

  1. Can you post a solution to this problem ?
    Is there a solution other than evaluating all possible combinations from 2 to 14 ?

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. EDIT: tried to correct indentation.

    "... None of his children have the same age". This has not been checked for in your solution.

    Here's the solution:

    import itertools;
    from operator import mul;

    def solveage():
      a = xrange(2,8);
      b = xrange(1,14);

      for i in a:
        agelist = xrange(1,14);
        combos = itertools.combinations(agelist, i);
        for combi in combos:
          rhs = pow(sum(combi),2);
          lhs = reduce(mul, combi)
          if lhs==rhs:
            print combi;

    result:
    (2, 4, 6, 12)
    (1, 2, 4, 8, 9)

    ReplyDelete
  4. Thanks divine for pointing it out. Updated the code. The change was instead of x in for loop, we have x-1

    ReplyDelete