string = 'abc'
. All subsets of said string are: [a b c ab abc ac bc '(empty string)']
.
I need to generate all of these subsets using a recursive function, but I can't figure out how.
Asked
Active
Viewed 1,717 times
-2
-
1First do it using ballpen and paper. – furas Jun 20 '14 at 00:36
-
1What have you tried so far? Hint: think about subsets of subsets and how that might relate to recursion. – Milo P Jun 20 '14 at 00:36
2 Answers
1
For each char recur to use and not use
s = 'abc'
def recur(s, prefix, out):
if len(s) > 0:
recur(s[1:], prefix+s[0], out)
recur(s[1:], prefix, out)
out.append(prefix+s[0])
return out
print recur(s, '', [''])
outputs
['', 'abc', 'ac', 'ab', 'bc', 'c', 'b', 'a']

Fabricator
- 12,722
- 2
- 27
- 40
0
Just for kicks, you can write it as a one line lambda.
lambda s: { s[j:(j+i)] for i in range(len(s)+1) for j in range(len(s)-i+1) }

Alec
- 31,829
- 7
- 67
- 114