[ Code Kata ] ๐Ÿคฏ๐Ÿฅต python #17 ์ฃผ์‹ ๊ฑฐ๋ž˜ ์ค‘ ๊ฐ€์žฅ ์ด์ต์ด ํฐ ๊ฐ’์€? / float('inf')

Haileeยท2020๋…„ 12์›” 22์ผ
0

[ Code Kata ]

๋ชฉ๋ก ๋ณด๊ธฐ
22/28
post-thumbnail

๋ฌธ์ œ

prices๋Š” ๋ฐฐ์—ด์ด๋ฉฐ, ๊ฐ ์š”์†Œ๋Š” ๋งค์ผ์˜ ์ฃผ์‹ ๊ฐ€๊ฒฉ์ž…๋‹ˆ๋‹ค.
๋งŒ์•ฝ ํ•œ ๋ฒˆ๋งŒ ๊ฑฐ๋ž˜ํ•  ์ˆ˜ ์žˆ๋‹ค๋ฉด = ์‚ฌ๊ณ  ํŒ” ์ˆ˜ ์žˆ๋‹ค๋ฉด, ์ œ์ผ ํฐ ์ด์ต์€ ์–ผ๋งˆ์ผ๊นŒ์š”?

  • ์˜ˆ๋ฅผ ๋“ค์–ด,
Input: [7,1,5,3,6,4]
Output: 5

2์ผ(๊ฐ€๊ฒฉ=1)์— ์ƒ€๋‹ค๊ฐ€ 5์ผ(๊ฐ€๊ฒฉ=6)์— ์‚ฌ๋Š” ๊ฒƒ์ด 6-1์ด๋ผ ์ œ์ผ ํฐ ์ˆ˜์ต
7-1=6 ์€ ์•ˆ ๋˜๋Š”๊ฑฐ ์•„์‹œ์ฃ ? ๋จผ์ € ์‚ฌ์•ผ ํŒ” ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

Input: [7,6,4,3,1]
Output: 0

์—ฌ๊ธฐ์„œ๋Š” ๋งค์ผ ๊ฐ€๊ฒฉ์ด ๋‚ฎ์•„์ง€๊ธฐ ๋•Œ๋ฌธ์— ๊ฑฐ๋ž˜๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค. ๊ทธ๋ž˜์„œ 0

๊ฐˆ์ˆ˜๋ก ์ˆ˜์ค€์ด ๋†’์•„์ง€๋Š” ์ฝ”๋“œ์นดํƒ€!
๊ณ„์†ํ•ด์„œ ์ด์–ด์ง€๋Š”,, ์ž…์ฒด์ ์œผ๋กœ ์ƒ๊ฐํ•ด์•ผ ํ•˜๋Š” ๋ฌธ์ œ๋“ค์˜ ์—ฐ์†์— ๋งฅ์—†์ด ์“ฐ๋Ÿฌ์ง€๋Š” ๊ฒƒ ๊ฐ™๋‹ค

๋ฌผ๋ก  ํ”„๋กœ์ ํŠธ ๋•Œ๋ฌธ์— ์•„์˜ˆ ์ฝ”๋“œ์นดํƒ€๋ฅผ ํ’€ ์—„๋‘๋„ ์—ฌ์œ ๋„ ์—†๊ธด ํ•˜์ง€๋งŒ..

prices๋ฐฐ์—ด์„ for loop์œผ๋กœ ๋Œ๋ฆฌ๋ฉด์„œ ๊ฐ ๊ฒฝ์šฐ๋งˆ๋‹ค ์–ด๋–ค ์ˆ˜์ต์ด ๋‚ ์ง€ ํ™•์ธํ•ด? ์ด๊ฒŒ ๋ง์ด ๋ผ..?
๊ทธ๋Ÿผ.. ๊ฒฝ์šฐ์˜ ์ˆ˜๊ฐ€.... 36๊ฐœ์•ผ..? ๋งž๋‚˜..?

model solution

def maxProfit(prices): 
  max_profit, min_price = 0, float('inf')
  
  for price in prices:
      min_price = min(min_price, price)
      profit = price - min_price
      max_profit = max(max_profit, profit)
      
  return max_profit

์ž ์—ญ์‹œ๋‚˜ ์˜ค๋Š˜๋„ float('inf')๊ฐ€ ๋ฌด์—‡์ธ์ง€ ๋ชจ๋ฅด๋Š” ๋‚˜..!!!
์ฒ˜์Œ์—” int๋ฅผ ์˜คํƒ€๋‚ธ ์ค„ ์•Œ์•˜๋Š”๋ฐ ์ €๊ฒŒ ์ง„์งœ ๋งž๋Š” ์ฝ”๋“œ์˜€๋‹ค. (์ถฉ๊ฒฉ)

์—ญ์‹œ ์„ธ์ƒ์€ ๋„“๊ณ  ์ฝ”๋“œ๋Š” ๋งŽ์•„

float('inf')

It acts as an unbounded upper value for comparison. This is useful for finding lowest values for something.
for example, calculating path route costs when traversing trees.

ํ•œ๋งˆ๋””๋กœ ์ง€๊ธˆ๊ณผ ๊ฐ™์€ ๋ฌธ์ œ ์ƒํ™ฉ์—์„œ, ๊ฐ€์žฅ ๊ฐ’์ด ์ ๊ฒŒ ๋‚˜์˜ค๋Š” ๊ฒฝ์šฐ๋ฅผ ์ฐพ์„ ์ˆ˜ ์žˆ๋Š” ํ•จ์ˆ˜!
๐Ÿ‘‰๐Ÿป What is the point of float('inf')?

Finding the "cheapest" path in a list of options: (์šฐ๋ฆฌ ๋ฌธ์ œ๋ž‘ ๋น„์Šทํ•˜๋‹ค)

>>> lowest_path_cost = float('inf')
>>> # pretend that these were calculated using some worthwhile algorithm
>>> path_costs = [1, 100, 2000000000000, 50]
>>> for path in path_costs:
...   if path < lowest_path_cost:
...     lowest_path_cost = path
...
>>> lowest_path_cost
1

It acts as an unbounded upper value for comparison. This is useful for finding lowest values for something. for example, calculating path route costs when traversing trees.

if you didn't have float('Inf') available to you, what value would you use for the initial lowest_path_cost? Would 9999999 be enough -- float('Inf') removes this guesswork.

profile
์›น ๊ฐœ๋ฐœ ๐Ÿท๐Ÿ˜Ž๐Ÿ‘Š๐Ÿป๐Ÿ”ฅ

0๊ฐœ์˜ ๋Œ“๊ธ€