I have the following python function to recursively search all sections 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 convert this to ruby? This is what I still have:
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". I think this is because yield functions work differently in Python and Ruby.
python ruby
tom
source share