Discussion - Python List Comprehensions; power set?
Hi,
I teach an introductory programming class in Python and the staff and I are trying to stump each other with some "challenge" list comprehension problems to give to our students as a fun optional problem. I'd love your take - can you think of any tricky ones? Additionally, we've been debating if you can generate a power set from a single list comprehension. I've come kind of close but always miss a few. Can anyone prove either side of the debate? (it would suffice to be able to generate a near-complete powerset, eg one that omits the empty set [] or generally gives 2**n - 1 elements) Thanks all, I look forward to reading your responses. Sarina |
It kind of depends on how you define a "set":
Quote:
Code:
range(2**s) Code:
[ [ x for x in range(int(floor(log(max(n,1)) / log(2) + 1))) if (1 << x) & n ] Code:
from math import log, floor |
Agreed I phrased the problem incorrectly.
By "power set" we mean to define the problem as follows: Given a list of numbers my_list = [1, 2, 3, 4], can you give a list comprehension that generates all possible subsets of my_list? So the list comprehension you gave is the basic idea. We have not visited this problem again since I posted the question but will update if one of us thinks of an elegant solution, or comes up with another fun challenge problem. |
Quote:
Code:
import itertools |
All times are GMT -5. The time now is 10:26 PM. |