I am trying to implement a function to generate the powerset of a list xs
.
The general idea is that we walk through the elements of xs
and choose whether to include x
or not. The problem I'm facing is that withX
ends up being equal to [None]
(a singleton list with None
) because (I think) s.add(x)
returns None
.
This isn't a homework assignment, it's an exercise in Cracking the Coding Interview.
def powerSetBF(xs):
powerSet = []
powerSet.append(set([]))
for x in xs:
powerSetCopy = powerSet[:]
withX = [s.add(x) for s in powerSetCopy] # add x to the list of sets
powerSet = powerSet.extend(withX) # append those entries
return powerSet
[s.add(x) for s in powerSetCopy]
definitely wrong. It will always be a list ofNone
s.s.add(x)
returnsNone
. – IllustratepowerSet = powerSet.extend(withX)
will assignNone
topowerSet
, asextend
modifies in place and returnsNone
. I recommend learning more about list manipulation in python. – Illustrate