I have the following python function to recursively find all partitions of a set:
def partitions(set_):
if not set_:
yield []
return
for i in xrange(2**len(set_)/2):
parts = [set(), set()]
for item in set_:
parts[i&1].add(item)
i >>= 1
for b in partitions(parts[1]):
yield [parts[0]]+b
for p in partitions(["a", "b", "c", "d"]):
print p
Can someone help me to translate this into ruby? This is what I have so far:
def partitions(set)
if not set
yield []
return
end
(0...2**set.size/2).each { |i|
parts = [Set.new, Set.new]
set.each { |item|
parts[i&1] << item
i >>= 1
}
partitions(parts[1]).each { |b|
yield [parts[0]] << b
}
}
end
p partitions([1, 2, 3, 4].to_set)
I get the error "LocalJumpError: no block given". I guess this is because the yield functions work differently in python and ruby.