S
Sam Kong
Hi!
I am trying to get a powerset (all subsets) of a set.
I couldn't find a code in Ruby, but I found a code in Python.
I'm trying to convert it to Ruby but it's not done easily.
def powset(seq):
if seq:
head, tail = seq[:1], seq[1:]
for smaller in powset(tail):
yield smaller
yield head + smaller
else:
yield []
1. Can somebody translate the Python code into Ruby?
(I have difficulty in understanding the yield part)
2. Actually I want to add a method to Set class.
How can I change the function into a method which won't take any
parameter.
(Can a method be recursive if it doesn't take a parameter?
Maybe not.
Do I need a helper private method?)
example:
s = Set[1,2,3]
ps = s.powerset #returns a set of powerset of s
Thanks.
Sam
I am trying to get a powerset (all subsets) of a set.
I couldn't find a code in Ruby, but I found a code in Python.
I'm trying to convert it to Ruby but it's not done easily.
def powset(seq):
if seq:
head, tail = seq[:1], seq[1:]
for smaller in powset(tail):
yield smaller
yield head + smaller
else:
yield []
1. Can somebody translate the Python code into Ruby?
(I have difficulty in understanding the yield part)
2. Actually I want to add a method to Set class.
How can I change the function into a method which won't take any
parameter.
(Can a method be recursive if it doesn't take a parameter?
Maybe not.
Do I need a helper private method?)
example:
s = Set[1,2,3]
ps = s.powerset #returns a set of powerset of s
Thanks.
Sam