def pick(x, lis, out, a = 0): if x == 0: out.append(a) return a *= 10 for i in xrange(len(lis)): tmp = lis[:] tmpa = a + lis[i] tmp.pop(i) pick(x - 1, tmp, out, tmpa) def isprime(x): if x == 2: return True if x % 2 == 0: return False temp = 3 while temp <= int(x ** 0.5) + 1: if x % temp == 0: return False else: temp += 2 return True a = [1,2,3,4,5,6,7] tt = [] pick(len(a), a, tt) tt.reverse() for i in tt: if isprime(i): print i break