Translating function for finding all partitions of a set from Python to Ruby

前端 未结 2 1370
死守一世寂寞
死守一世寂寞 2020-12-11 18:09

I have the following python function to recursively find all partitions of a set:

def partitions(set_):
    if not set_:
        yield []
        return
             


        
相关标签:
2条回答
  • 2020-12-11 19:01

    You'll have to think of Ruby's yield like a call to a user-defined operation.

    def twice
        yield
        yield
    end
    
    twice { puts "Hello" } 
    

    So whenever your code yields a value, a processing function for this element will be called.

    partitions([1, 2, 3, 4].to_set) { |result| 
        # process result
    }
    

    This code doesn't generate a list at all.

    0 讨论(0)
  • 2020-12-11 19:06
    #!/usr/bin/ruby1.8
    
    def partitions(set)
      yield [] if set.empty?
      (0 ... 2 ** set.size / 2).each do |i|
        parts = [[], []]
        set.each do |item|
          parts[i & 1] << item
          i >>= 1
        end
        partitions(parts[1]) do |b|
          result = [parts[0]] + b
          result = result.reject do |e|
            e.empty?
          end
          yield result
        end
      end
    end
    
    partitions([1, 2, 3, 4]) do |e|
      p e
    end
    
    # => [[1, 2, 3, 4]]
    # => [[2, 3, 4], [1]]
    # => [[1, 3, 4], [2]]
    # => [[3, 4], [1, 2]]
    # => [[3, 4], [2], [1]]
    # => [[1, 2, 4], [3]]
    # => [[2, 4], [1, 3]]
    # => [[2, 4], [3], [1]]
    # => [[1, 4], [2, 3]]
    # => [[1, 4], [3], [2]]
    # => [[4], [1, 2, 3]]
    # => [[4], [2, 3], [1]]
    # => [[4], [1, 3], [2]]
    # => [[4], [3], [1, 2]]
    # => [[4], [3], [2], [1]]
    

    What's different:

    • The guard calls set.empty? instead of (implicitly) testing for set.nil?
    • Leave out the .each when calling partitions
    • Use Array instead of Set
    • Filter empty sets out of the yielded result
    0 讨论(0)
提交回复
热议问题