Translate from Python to Ruby

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

Sam K. wrote:

        yield smaller
        yield head + smaller
else:
    yield []
  1. Can somebody translate the Python code into Ruby?
    (I have difficulty in understanding the yield part)

def powset seq
unless seq.empty?
head,tail = seq[0,1] , seq[1…-1]
powset(tail){|smaller|
yield smaller
yield head + smaller
}
else
yield []
end
end

powset([1,2,5]){|e| p e}

not sure if it works for other examples

lopex

Non-recursive version:
I’m sure you can translate this for sets…

class Array
def powset
ret = []
0.upto(2**size - 1) do |n|
ret << []
0.upto(size - 1) do |i|
ret.last << self[i] if (n & (1 << i)) != 0
end
end
ret
end
end

p [].powset
p [1].powset
p [1,2].powset
p [1,2,3].powset
[[]]
[[], [1]]
[[], [1], [2], [1, 2]]
[[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]

Sorry, i couldn’t resist:

class Array
def powset
(0…(2**size)).map do |n|
(0…size).reject{|i|n[i].zero?}.map{|i|at(i)}
end
end
end

cheers

Simon

require ‘set’

class Set
def powerset
result = Set.new
for element_map in 0…(1 << self.length) do
subset = Set.new
each_with_index do |element, index|
subset.add(element) if element_map[index] == 1
end
result.add(subset)
end
return result
end
end

s = Set[1,2,3]
ps = s.powerset #returns a set of powerset of s
p ps

Sam K. wrote:

else:
    yield []

Here’s mine. It’s not 1:1, but you should be able to recognize the
original concept.

Feel free to ask any questions you might have about the code.

TRANS, are you listening? :slight_smile:

  • Simon Kr?ger (removed_email_address@domain.invalid) wrote:

Sorry, i couldn’t resist:

class Array
def powset
(0…(2**size)).map do |n|
(0…size).reject{|i|n[i].zero?}.map{|i|at(i)}
end
end
end

lovely peace of code!
(it makes my brain burning but its nice!)

class Array
end

So long

Michael ‘entropie’ Trommer; http://ackro.org

ruby -e “0.upto((a=‘njduspAhnbjm/dpn’).size-1){|x| a[x]-=1}; p
‘mailto:’+a”