-
-
Save miloshadzic/7684437 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#reduce(function, sequence) | |
print reduce(lambda x, y: x+y, range(1,11)) | |
def red(funct, seq): | |
for x in seq: #do this for every x in this list | |
return funct(seq) # ovde ti je greska zbog toga sto ce ovaj return da vrati | |
# rezultat poziva funct(seq) vec na prvom elementu. Probaj da prvo napravis | |
# promenljivu u kojoj ces drzati rezultat. To ti je "akumulator". Dodatni hint | |
# je ispod -v | |
def adding(x): | |
return sum(x) | |
# sum je funkcija koja prima listu i vraca sumu elemenata iste. Funkcija koju | |
# prosleđuješ u reduce bi trebalo da prima dva argumenta od kojih je jedan | |
# trenutni element a druga trenutno stanje akumulatora. Npr: | |
reduce(lambda acc, x: acc + x, range(1,10)) #=> 45 | |
# Evo nekoliko test slučajeva da ti bude lakše | |
print red(lambda acc, x: acc + x, range(1,10)) == 45 | |
print red(lambda acc, x: acc * x, range(1,10)) == 362880 | |
# Reduce vraca jednu vrednost, tako sto redom uzima clanove liste i u ovom | |
# slucaju ih sabira , ili poziva prvi argument(funkciju) i primenjuje ga na | |
# prva dva clana liste(drugi argument), onda sa tim zbirom poziva funkciju | |
# koja se implementira sa sledecim clanom i tako do kraja liste. Na kraju | |
# vrati jedinicnu vrednost. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment