all possible combinations

rbt rbt at athop1.ath.vt.edu
Wed Jul 13 17:09:25 CEST 2005


On Wed, 2005-07-13 at 10:21 -0400, rbt wrote:
> Say I have a list that has 3 letters in it:
> 
> ['a', 'b', 'c']
> 
> I want to print all the possible 4 digit combinations of those 3
> letters:
> 
> 4^3 = 64
> 
> aaaa
> abaa
> aaba
> aaab
> acaa
> aaca
> aaac
> ...
> 
> What is the most efficient way to do this? 

Expanding this to 4^4 (256) to test the random.sample function produces
interesting results. It never finds more than 24 combinations out of the
possible 256. This leads to the question... how 'random' is sample ;)

Try it for yourselves:

test = list('1234')

combinations = []
while 1:
    combo = random.sample(test, 4)
    possibility = ''.join(combo)
    if possibility not in combinations:
        print possibility    
        combinations.append(possibility)
        continue
    else:
        continue




More information about the Python-list mailing list