问题描述
我在寻找一个具有如Python的 itertools.product
在Ruby中同样效果的方法。看看下面的Python code:
I'm looking for a method that has the same effect as Python's itertools.product
in Ruby. Take the following Python code:
from itertools import product
chars = []
for i in range(97,123):
chars.append(chr(i))
for a in range(1,3):
for i in product(chars,repeat=a):
s = ''.join(i)
print s
这输出是这样的:
a, b, c... x, y, z, aa, ab, ac... ax, ay, az, ba, bb, bc.. etc.
我试着翻译成红宝石:
I tried to translate that into Ruby:
(1..2).each do |n|
('a'..'z').to_a.combination(n).each do |c|
s = c.join
puts s
end
end
但输出是不一样的。单字符那些做工精细(A-Z),但是当它进入两个字符的人,如我所料不工作:
But the output isn't the same. The one-character ones work fine (a-z), but when it goes into two-character ones, it doesn't work as I expected:
ab, ac, ad.. ax, ay, az, bc, bd, be
它不产生 AA
, BA
或 BB
- 因此它看起来它生成所有组合,而无需重复字符或什么
It isn't generating aa
, ba
or bb
- so it appears it's generating all the combinations without repeating characters or something?
所以,我应该用什么方法来生成的所有的如 itertools.product
组合确实在Python?
So what method should I use to generate all the combinations like itertools.product
does in Python?
推荐答案
我会写(简化为3个元素,Ruby 1.9的要求):
I would write (simplified for 3 elements, Ruby 1.9 required):
xs = ["a", "b", "c"]
strings = 1.upto(xs.size).flat_map do |n|
xs.repeated_permutation(n).map(&:join)
end
#=> ["a", "b", "c", "aa", "ab", "ac", ..., "cca", "ccb", "ccc"]
一个懒惰的解决方案:你可以很容易地将其与写每个
的S代替地图
S,但让我们检查懒在Ruby 2.0:
A lazy solution: you could easily write it with each
s instead of map
s, but let's check "lazy" from Ruby 2.0:
xs = ("a".."z").to_a
strings = 1.upto(xs.size).lazy.flat_map do |n|
xs.repeated_permutation(n).lazy.map(&:join)
end
这篇关于什么是Python的Ruby中itertools.product相当于?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!