Powersets of a list?

David C. Ullrich ullrich at math.okstate.edu
Fri May 25 17:30:46 CEST 2001


On Fri, 25 May 2001 09:57:41 -0400, Roy Katz <katz at Glue.umd.edu>
wrote:

>Hello,
>
>I was wondering if, given a list  [1,2,3], one can generate its power set?

Well, a list is not a set - if a list is a "set with repetitions" then
the following returns the "set-with-repetitions power set":

def AddTo(list, elt):
	return list + [elt]

def PowerSet(list):
  if list:
    ans = PowerSet(list[:-1])
    return ans + map(AddTo, ans, [list[-1]]*len(ans))
  else:
    return [[]]

Probably the slowest possible solution...

>thanks,
>Roey Katz
>
>

David C. Ullrich
***********************
"Sometimes you can have access violations all the
time and the program still works." (Michael Caracena,
comp.lang.pascal.delphi.misc 5/1/01)



More information about the Python-list mailing list