我想知道如何将这段Python代码翻译成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
- 我的要求尝试:
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
答案 0 :(得分:1)
我不确定是否有从python转换为ruby的一般方法,但至少在你的例子中,它可以通过使用Enumerator Class进行翻译,如下所示。
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