Working on Problem Set 6 problem 4, it is required to generate all subsets of a list.
The easiest way is to recursive in my understanding. If I can generate all subsets of a list without the first element (that's list[1:]), and store it in a container, then iterate through the container A, and combine the first element, then store the combined result in container B. Container A and B all together should be the result.
I have great difficulty to implement this. I think I don't learn python well enough to write the code ... Anybody help me out!
At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga.
Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus.
Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.
I googled, and found the following code works. But I can't understand why it is so...
if x == :
s = [x]
for elem in x:
tmp = x[:]
new_sub = subsets(tmp)
for y in new_sub: # <-- can't just make it a set(), because lists aren't hashable.
if y not in s:
i pasted your code to dpaste... it is here http://dpaste.com/535552/
sometimes its hard to wrap your head around a recursive algorithm
at line 6 it starts a loop. line 8 removes an element from the list. then line 9 calls the function (itself) with the new list. this is the first 'instance' of the function and it just gets paused at line 9 till the recursions all get done.
so at line 9 when it calls itself a new instance of of the function runs lines 2-9 again. this keeps happening until finally there aren't any elements left in the list and lines 2,3 return without calling itself again.
at this point the very last instance has returned an empty list and - whoops the next line didn't work for the empty list
i passed a list to the function, maybe it was expecting something else.
at least that is how it looks like it was meant to work. i tried it and it didn't work so i put some print statements in to try to see what is happening - the print statements might help understand the recursion part.. http://dpaste.com/535569/
don't put to many elements in the list, it will print a lot.!!
"Recursion is the process of repeating items in a self-similar way. For instance, when the surfaces of two mirrors are exactly parallel with each other the nested images that occur are a form of infinite recursion."
from this wipedia article: http://en.wikipedia.org/wiki/Recursion
i like the parallel mirror analogy.