logo

ridurre() in Python

IL ridurre(divertimento,seq) la funzione è utilizzata applicare una particolare funzione passata nel suo argomento a tutti gli elementi della lista menzionato nella sequenza passata. Questa funzione è definita in funtools modulo.

Lavorando :

  • Nella prima fase vengono selezionati i primi due elementi della sequenza e si ottiene il risultato.
  • Il passo successivo è applicare la stessa funzione al risultato ottenuto in precedenza e il numero appena successivo al secondo elemento e il risultato vengono nuovamente memorizzati.
  • Questo processo continua finché non rimangono più elementi nel contenitore.
  • Il risultato finale restituito viene restituito e stampato sulla console.

Python3






# python code to demonstrate working of reduce()> > # importing functools for reduce()> import> functools> > # initializing list> lis>=> [>1>,>3>,>5>,>6>,>2>]> > # using reduce to compute sum of list> print>(>'The sum of the list elements is : '>, end>=>'')> print>(functools.>reduce>(>lambda> a, b: a>+>b, lis))> > # using reduce to compute maximum element from list> print>(>'The maximum element of the list is : '>, end>=>'')> print>(functools.>reduce>(>lambda> a, b: a>if> a>b>else> b, lis))>

>

>

Produzione

The sum of the list elements is : 17 The maximum element of the list is : 6>

Utilizzo delle funzioni operatore

reduce() può anche essere combinato con funzioni operatore per ottenere funzionalità simili a quelle delle funzioni lambda e rendere il codice più leggibile.

Python3




# python code to demonstrate working of reduce()> # using operator functions> > # importing functools for reduce()> import> functools> > # importing operator for operator functions> import> operator> > # initializing list> lis>=> [>1>,>3>,>5>,>6>,>2>]> > # using reduce to compute sum of list> # using operator functions> print>(>'The sum of the list elements is : '>, end>=>'')> print>(functools.>reduce>(operator.add, lis))> > # using reduce to compute product> # using operator functions> print>(>'The product of list elements is : '>, end>=>'')> print>(functools.>reduce>(operator.mul, lis))> > # using reduce to concatenate string> print>(>'The concatenated product is : '>, end>=>'')> print>(functools.>reduce>(operator.add, [>'geeks'>,>'for'>,>'geeks'>]))>

convertire nfa in dfa

>

>

Produzione

The sum of the list elements is : 17 The product of list elements is : 180 The concatenated product is : geeksforgeeks>

ridurre() vs accumulare()

Sia reduce() che accumulate() possono essere utilizzati per calcolare la somma degli elementi di una sequenza. Ma ci sono differenze negli aspetti implementativi in ​​entrambi.

  • reduce() è definito nel modulo functools, accumulate() nel modulo itertools.
  • reduce() memorizza il risultato intermedio e restituisce solo il valore della somma finale. Mentre accumulate() restituisce un iteratore contenente i risultati intermedi. L'ultimo numero dell'iteratore restituito è il valore di somma dell'elenco.
  • reduce(fun, seq) accetta la funzione come primo argomento e la sequenza come secondo argomento. Al contrario accumulate(seq, fun) accetta la sequenza come primo argomento e la funzione come secondo argomento.

Python3




# python code to demonstrate summation> # using reduce() and accumulate()> > # importing itertools for accumulate()> import> itertools> > # importing functools for reduce()> import> functools> > # initializing list> lis>=> [>1>,>3>,>4>,>10>,>4>]> > # printing summation using accumulate()> print>(>'The summation of list using accumulate is :'>, end>=>'')> print>(>list>(itertools.accumulate(lis,>lambda> x, y: x>+>y)))> > # printing summation using reduce()> print>(>'The summation of list using reduce is :'>, end>=>'')> print>(functools.>reduce>(>lambda> x, y: x>+>y, lis))>

>

>

Produzione

The summation of list using accumulate is :[1, 4, 8, 18, 22] The summation of list using reduce is :22>

funzione reduce() con tre parametri

La funzione Reduce, ovvero la funzione reduce(), funziona con 3 parametri in python3 e con 2 parametri. Per dirla in modo semplice reduce() pone il 3° parametro prima del valore del secondo, se presente. Pertanto, significa che se il 2° argomento è una sequenza vuota, il 3° argomento funge da predefinito.

Ecco un esempio :(Questo esempio è stato preso da documentazione functools.reduce() include una versione Python della funzione:

Python3

eredità Java




# Python program to illustrate sum of two numbers.> def> reduce>(function, iterable, initializer>=>None>):> >it>=> iter>(iterable)> >if> initializer>is> None>:> >value>=> next>(it)> >else>:> >value>=> initializer> >for> element>in> it:> >value>=> function(value, element)> >return> value> > # Note that the initializer, when not None, is used as the first value instead of the first value from iterable , and after the whole iterable.> tup>=> (>2>,>1>,>0>,>2>,>2>,>0>,>0>,>2>)> print>(>reduce>(>lambda> x, y: x>+>y, tup,>6>))> > # This code is contributed by aashutoshjha>

>

>

Produzione

15>

Questo articolo è stato fornito da Manjeet Singh(S. Nandini) .