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

前端 未结 2 1374
死守一世寂寞
死守一世寂寞 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条回答
  •  萌比男神i
    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

提交回复
热议问题