Finding tuples of numbers subject to constraints I just watched the video from "Think Like a Programmer, Episode 2: Puzzles &amp; Problems".

The problem is: 


  Assign number 1-7 to three departments in a city: Fire, Police,
  Sanitation.
  
  Requirement:
  
  
  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 itertools:

import itertools


all_permutations = list(itertools.permutations(numbers, 3))

for each_p in all_permutations:
    f, p, s = each_p[0], each_p[1], each_p[2]
    if valid_department_number(f, p, s):
        print(each_p)


The 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.
f != p != s does not prevent f and s from being equal

You can improve your algorithmic approach, using your constraints:

def iter_permutations():
    total = 12
    for f in range(1, 8):        # Fire must be between 1 and 7
        for p in range(2, 8, 2): # Police must be even
            s = total - p - f    # The sum must be 12
            if 0 &lt; s &lt; 8 and f != p != s != f: # They must be all different
                 yield f, p, s   # Use an iterator, because it's elegant!


You can simply use it with : for f, p, s in iter_permutations():

I think using an iterator is nicer than a list (you can easily get a list with list(iter_permutations()) if needed)