Thanks castironpi and alex, for this: def p(a,b): if not b: return [''] return [i+j for i in a for j in p(a,b-1)]
That is a thing of beauty! As usual you guys didn't disappoint. (Validity check of alphabet removed; you didn't check for duplicate characters.) Here is the bloated mess I came up with. I did see that it had to be recursive, and was proud of myself for getting it pretty much on the first try, but the thing still reeks of my sorry old fortran-addled mentality. def validAlphabet(alphabet): if not isinstance(alphabet,str): return False if len(alphabet) > 256: return False for index in range(len(alphabet)-1): if not alphabet[index] < alphabet[index+1]: return False return True def nextword(word,alphabet): if len(word) == 1: index = alphabet.find(word) if index < 0: raise ValueError("bad token found %s" % word) if index == len(alphabet) -1: return None else: return alphabet[index+1] else: a = nextword(word[1:],alphabet) if a: return word[0] + a else: b = nextword(word[0],alphabet) if b: return b + (len(word) - 1) * alphabet[0] else: return None def allwords(length,alphabet="01"): if not validAlphabet(alphabet): raise ValueError("bad token list %s" % alphabet) word = length * alphabet[0] result = [word] while word < length * alphabet[-1]: word = nextword(word,alphabet)) result.append(word) return result ###### if __name__ == "__main__": for item in allwords(5,"abc"): print item -- http://mail.python.org/mailman/listinfo/python-list