generate all combinations of a list (with variable output length)
Bengt Richter
bokr at oz.net
Fri Jun 28 18:46:42 EDT 2002
On Fri, 28 Jun 2002 15:09:47 -0500, "Mark McEahern" <marklists at mceahern.com> wrote:
>> i'm looking for a way to generate all possible combinations of all items
>> in a list. list = ["A","D","$","5","R"]
>
>i don't have a solution, but some questions to clarify:
>
>if you think of your list as comprising the digits, then you're asking for
>an n-length string composed of all possible digits where the digits include:
>
> A, D, $, 5, R, and None (the representation of the latter is '')
>
>so, for n = 10, this is a possible value:
>
> AAAAAAAAAA
>
>as well as:
>
> [ ]
>
>omit the brackets.
>
>True?
>
>anyway, this might get you started:
>
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/105962
>
>// m
>
Or, implementing your base-5 digits idea, and leaving out '':
>>> def adD5r(n):
... codes='AD$5R' # <=> 01234
... out = []; m = n
... while 1:
... n,d = divmod(n,5)
... out.append(codes[d])
... if not n:break
... out.reverse()
... return '%d:%s' % (m,''.join(out))
...
>>> [adD5r(5**n) for n in range(5)]
['1:D', '5:DA', '25:DAA', '125:DAAA', '625:DAAAA']
>>> [adD5r(5**n+1) for n in range(5)]
['2:$', '6:DD', '26:DAD', '126:DAAD', '626:DAAAD']
>>> [adD5r(n) for n in range(26)]
['0:A', '1:D', '2:$', '3:5', '4:R', '5:DA', '6:DD', '7:D$', '8:D5', '9:DR', '10:$A', '11:$
D', '12:$$', '13:$5', '14:$R', '15:5A', '16:5D', '17:5$', '18:55', '19:5R', '20:RA', '21:R
D', '22:R$', '23:R5', '24:RR', '25:DAA']
The smallest and biggest 10-"digit" numbers would be
>>> adD5r(0)
'0:A'
(I'll leave it as an exercise for the OP to prefix leading "zeroes" to desired print width
for that set of strings ;-)
>>> adD5r(5**10-1)
'9765624:RRRRRRRRRR'
generated analogously to
>>> 10**10-1
9999999999L
Regards,
Bengt Richter
More information about the Python-list
mailing list