【问题标题】:Ruby array product with asterisk带有星号的 Ruby 数组产品
【发布时间】:2015-04-04 11:51:28
【问题描述】:

我正在研究如何列出一个数字的所有除数,并遇到了 Marc-Andre here 的这个解决方案。在他的解决方案中,有一部分代码做了这样的事情:

array.product(*arrays_of_array) # the asterisk seems to have done sth.

我在 irb 中尝试过尝试玩耍,但我无法理解输出。我试过了:

a=[0,1,2]
b=[3,4]
c=[[5,6],[7,8]]

我了解array.product(other_array) 是一种将两个数组的所有组合合并为一个的方法。有了这些知识,我测试了几个实验

a.product(b)      => [[0, 3], [0, 4], [1, 3], [1, 4], [2, 3], [2, 4]] / 6 elements
a.product(*b)     => TypeError: no implicit conversion of Fixnum into Array
a.product(c)      => [[0, [5, 6]], [0, [7, 8]], [1, [5, 6]], [1, [7, 8]], [2, [5, 6]], [2, [7, 8]]] / 6 elements
a.product(*c)     => [[0, 5, 7], [0, 5, 8], [0, 6, 7], [0, 6, 8], [1, 5, 7], [1, 5, 8], [1, 6, 7], [1, 6, 8], [2, 5, 7], [2, 5, 8], [2, 6, 7], [2, 6, 8]]

从观察来看,asterisk (*) 似乎必须应用于多维数组? (即矩阵?)。没有星号,产品返回 6 个元素,组合只返回一个级别。使用星号时,组合将更深 1 级并返回 12 个元素,并组合直到组合中没有数组。在哪里可以找到更多示例来研究星号的这种行为?


编辑:

我尝试再引入一个变量

d=[[[9,0],[1,2]],[[3,4],[5,6]]]
a.product(*d) => [[0, [9, 0], [3, 4]], [0, [9, 0], [5, 6]], [0, [1, 2], [3, 4]], [0, [1, 2], [5, 6]], [1, [9, 0], [3, 4]], [1, [9, 0], [5, 6]], [1, [1, 2], [3, 4]], [1, [1, 2], [5, 6]], [2, [9, 0], [3, 4]], [2, [9, 0], [5, 6]], [2, [1, 2], [3, 4]], [2, [1, 2], [5, 6]]]

所以星号只会让它更深一层。


在查找除数列表的上下文中。谁能解释一下代码到底是做什么的?

require 'prime'

def factors_of(number)
    primes, powers = number.prime_division.transpose
    exponents = powers.map{|i| (0..i).to_a}
    divisors = exponents.shift.product(*exponents).map do |powers|
        primes.zip(powers).map{|prime, power| prime ** power}.inject(:*)
    end
    divisors.sort.map{|div| [div, number / div]}
end

p factors_of(4800) # => [[1, 4800], [2, 2400], ..., [4800, 1]]

【问题讨论】:

    标签: ruby arrays


    【解决方案1】:

    *(splat) 用于扩展集合。

    在你的例子中,b = [3,4]

    a.product(*b)
    

    等价于

    a.product(3, 4)
    

    这会产生错误,因为Array#product 需要一个数组作为参数,而不是两个整数。

    【讨论】:

    • 谢谢@yuhao 您能否扩展您的解决方案以使用 a.product(*c) 作为另一个示例来说明它将如何扩展?顺便说一句,谢谢你的回答!
    • @ChrisYeung a.product(*c) => a.product([5,6],[7,8]
    猜你喜欢
    • 2015-02-19
    • 1970-01-01
    • 2014-02-16
    • 2016-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-15
    • 2015-10-07
    相关资源
    最近更新 更多