I was wondering how to translate this bit of Python code into Ruby:
from __future__ import generators
def xcombinations(items, n):
if n==0: yield []
else:
for i in xrange(len(items)):
for cc in xcombinations(items[:i]+items[i+1:],n-1):
yield [items[i]]+cc
-- my attempt at request:
def xcombinations(items, n)
Fiber.new do
if n == 0
Fiber.yield []
else
for i in 0...items.length
xcombinations(items[0...i]+items[i+1..-1],n-1).resume.each do |cc|
Fiber.yield [items[i]] << cc
end
end
end
end
end
I'm not sure there is a general way to translate from python to ruby but at least your example, it can be translated by using Enumerator Class as follows.
def xcombinations(items, n)
Enumerator.new do |y|
if n == 0 then
y << []
else
for i in 0...items.length
xcombinations(items[0...i]+items[i+1..-1],n-1).each do |cc|
y << [items[i]]+cc
end
end
end
end
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.