Domanda

Mi chiedo se c'è un modo per fare quello che posso fare di seguito con Python, in Ruby:

sum = reduce(lambda x, y: x + y, map(lambda x, y: x * y, weights, data))

Ho due array di uguali dimensioni con pesi e dati ma non riesco a trovare una funzione simile a map in Ruby, riduci che sto lavorando.

È stato utile?

Soluzione

@Michiel de Mare

Il tuo esempio Ruby 1.9 può essere ulteriormente accorciato:

weights.zip(data).map(:*).reduce(:+)

Tieni inoltre presente che in Ruby 1.8, se hai bisogno di ActiveSupport (da Rails) puoi utilizzare:

weights.zip(data).map(&:*).reduce(&:+)

Altri suggerimenti

In Rubino 1.9:

weights.zip(data).map{|a,b| a*b}.reduce(:+)

In Rubino 1.8:

weights.zip(data).inject(0) {|sum,(w,d)| sum + w*d }

La funzione Array.zip esegue una combinazione elementare di array.Non è così pulito come la sintassi Python, ma ecco un approccio che potresti usare:

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

Ruby ha un map metodo (ovveroIL collect metodo), che può essere applicato a qualsiasi Enumerable oggetto.Se numbers è un array di numeri, la seguente riga in Ruby:

numbers.map{|x| x + 5}

è l'equivalente della seguente riga in Python:

map(lambda x: x + 5, numbers)

Per maggiori dettagli, vedere Qui O Qui.

Un'alternativa per la mappa che funziona anche per più di 2 array:

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}

Questo potrebbe anche essere aggiunto a Array:

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 
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top