I just watched the video from "Think Like a Programmer, Episode 2: Puzzles & Problems".
The problem is:
Assign number 1-7 to three departments in a city: Fire, Police, Sanitation.
- Each department should have a unique number
- Police should be an even number
- Fire + Police + Sanitation = 12
Generate a list of permutations for these department numbers.
Here is my Python attempt:
def valid_department_number(f, p, s): if (f != p != s) and (f+p+s == 12) and p % 2 == 0: return True else: return False numbers = range(1, 8) for f in numbers: for p in numbers: for s in numbers: if valid_department_number(f, p, s): print(f, p, s)
I searched the python documentation and found that I could use the
permutations function from
import itertools all_permutations = list(itertools.permutations(numbers, 3)) for each_p in all_permutations: f, p, s = each_p, each_p, each_p if valid_department_number(f, p, s): print(each_p)
permutation function gets rid of three levels of nested
for loops. I'm wondering whether there's a better way to deconstruct the tuples from
permutation generated list of tuples.