質問
Python で以下にできることを Ruby で実行する方法があるかどうか疑問に思っています。
sum = reduce(lambda x, y: x + y, map(lambda x, y: x * y, weights, data))
重みとデータを含む同じサイズの2つの配列がありますが、Rubyのmapに似た関数が見つからないようです。reduceは機能しています。
解決
@ミシェル・デ・メア
Ruby 1.9 の例はさらにもう少し短縮できます。
weights.zip(data).map(:*).reduce(:+)
また、Ruby 1.8 では、(Rails からの) ActiveSupport が必要な場合は、以下を使用できることにも注意してください。
weights.zip(data).map(&:*).reduce(&:+)
他のヒント
Ruby 1.9 では:
weights.zip(data).map{|a,b| a*b}.reduce(:+)
Ruby 1.8では:
weights.zip(data).inject(0) {|sum,(w,d)| sum + w*d }
Array.zip 関数は、配列を要素ごとに組み合わせます。Python 構文ほど明確ではありませんが、使用できるアプローチの 1 つを次に示します。
weights = [1, 2, 3]
data = [4, 5, 6]
result = Array.new
a.zip(b) { |x, y| result << x * y } # For just the one operation
sum = 0
a.zip(b) { |x, y| sum += x * y } # For both operations
3 つ以上の配列でも機能するマップの代替案:
def dot(*arrays)
arrays.transpose.map {|vals| yield vals}
end
dot(weights,data) {|a,b| a*b}
# OR, if you have a third array
dot(weights,data,offsets) {|a,b,c| (a*b)+c}
これを配列に追加することもできます。
class Array
def dot
self.transpose.map{|vals| yield vals}
end
end
[weights,data].dot {|a,b| a*b}
#OR
[weights,data,offsets].dot {|a,b,c| (a*b)+c}
weights = [1,2,3]
data = [10,50,30]
require 'matrix'
Vector[*weights].inner_product Vector[*data] # => 200
所属していません StackOverflow