Solution to question asked by acit foo uses recursion, bar uses itertools and list comprehension.