๐ŸŒฑ โ†’ ๐ŸŒณ

python reduce ํ•จ์ˆ˜ ๋ณธ๋ฌธ

Server/Python

python reduce ํ•จ์ˆ˜

thals0 2023. 8. 13. 12:31
728x90

reduce ํ•จ์ˆ˜

ํŒŒ์ด์ฌ์˜ functols ๋‚ด์žฅ ๋ชจ๋“ˆ์˜ reduce() ํ•จ์ˆ˜๋Š” ์—ฌ๋Ÿฌ ๊ฐœ์˜ ๋ฐ์ดํ„ฐ๋ฅผ ๋Œ€์ƒ์œผ๋กœ ์ฃผ๋กœ ๋ˆ„์  ์ง‘๊ณ„๋ฅผ ๋‚ด๊ธฐ ์œ„ํ•ด์„œ ์‚ฌ์šฉ๋จ

 

๊ธฐ๋ณธ ๋ฌธ๋ฒ•์€ ์•„๋ž˜์™€ ๊ฐ™์Œ 

reduce(์ง‘๊ณ„ ํ•จ์ˆ˜, ์ˆœํšŒ ๊ฐ€๋Šฅํ•œ ๋ฐ์ดํ„ฐ[, ์ดˆ๊ธฐ๊ฐ’])

๊ธฐ๋ณธ์ ์œผ๋กœ ์ดˆ๊ธฐ๊ฐ’์„ ๊ธฐ์ค€์œผ๋กœ ๋ฐ์ดํ„ฐ๋ฅผ ๋ฃจํ”„ ๋Œ๋ฉด์„œ ์ง‘๊ณ„ ํ•จ์ˆ˜๋ฅผ ๊ณ„์†ํ•ด์„œ ์ ์šฉํ•˜๋ฉด์„œ ๋ฐ์ดํ„ฐ๋ฅผ ๋ˆ„์ ํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ ์ž‘๋™

 

์ง‘๊ณ„ ํ•จ์ˆ˜๋Š” ๋‘๊ฐœ์˜ ์ธ์ž๋ฅผ ๋ฐ›์•„์•ผ ํ•จ

์ฒซ๋ฒˆ์งธ ์ธ์ž๋Š” ๋ˆ„์ ์ž(accumulator), ๋‘๋ฒˆ์งธ ์ธ์ž๋Š” ํ˜„์žฌ๊ฐ’(current value)๊ฐ€ ๋„˜์–ด์˜ค๊ฒŒ ๋จ

๋ˆ„์ ์ž๋Š” ํ•จ์ˆ˜ ์‹คํ–‰์˜ ์‹œ์ž‘๋ถ€ํ„ฐ ๋๊นŒ์ง€ ๊ณ„์†ํ•ด์„œ ์žฌ์‚ฌ์šฉ๋˜๋Š” ๊ฐ’์ด๊ณ , ํ˜„์žฌ๊ฐ’์€ ๋ฃจํ”„ ๋Œ๋ฉด์„œ ๊ณ„์†ํ•ด์„œ ๋ฐ”๋€Œ๋Š” ๊ฐ’

 

์˜ˆ๋ฅผ ๋“ค์–ด arr์˜ ๋ชจ๋“  ์š”์†Œ๋ฅผ ๊ณฑํ•œ๋‹ค๊ณ  ๊ฐ€์ •ํ–ˆ์„ ๋•Œ 

from functools import reduce

answer = reduce(lambda x, y: x * y, arr)

์ด๋Ÿฐ ์‹์œผ๋กœ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Œ 

 

reference

https://www.daleseo.com/python-functools-reduce/

 

ํŒŒ์ด์ฌ reduce ํ•จ์ˆ˜ ์‚ฌ์šฉ๋ฒ•

Engineering Blog by Dale Seo

www.daleseo.com

 

728x90