--- title: 'Python Challenge Day 1 - Closest elevator' disqus: hackmd --- ## Python Challenge Day 1 - Closest elevator ### DESCRIPTION Given 2 elevators (named "left" and "right") in a building with 3 floors (numbered 0 to 2), write a function elevator accepting 3 arguments (in order): left - The current floor of the left elevator right - The current floor of the right elevator call - The floor that called an elevator It should return the name of the elevator closest to the called floor ("left"/"right"). In the case where both elevators are equally distant from the called floor, choose the elevator to the right. You can assume that the inputs will always be valid integers between 0-2. ### Examples: ```gherkin= elevator(0, 1, 0); // => "left" elevator(0, 1, 1); // => "right" elevator(0, 1, 2); // => "right" elevator(0, 0, 0); // => "right" elevator(0, 2, 1); // => "right" ``` 程式邏輯 --- 目的:選擇離呼叫樓層近的電梯 例外:若左右電梯在同一層,則選擇右側電梯 1. left - call >= right - call print(right) 2. left - call < right - call print(left) Solution --- ``` python def elevator(left, right, call): if abs(left-call) >= abs(right-call): return "right" else: return "left" ``` * 使用 def 關鍵字來定義函數(elevator--- title: 'Python Challenge Day 1 - Closest elevator' disqus: hackmd --- ## Python Challenge Day 1 - Closest elevator ### DESCRIPTION Given 2 elevators (named "left" and "right") in a building with 3 floors (numbered 0 to 2), write a function elevator accepting 3 arguments (in order): left - The current floor of the left elevator right - The current floor of the right elevator call - The floor that called an elevator It should return the name of the elevator closest to the called floor ("left"/"right"). In the case where both elevators are equally distant from the called floor, choose the elevator to the right. You can assume that the inputs will always be valid integers between 0-2. ### Examples: ```gherkin= elevator(0, 1, 0); // => "left" elevator(0, 1, 1); // => "right" elevator(0, 1, 2); // => "right" elevator(0, 0, 0); // => "right" elevator(0, 2, 1); // => "right" ``` 程式邏輯 --- 目的:選擇離呼叫樓層近的電梯 例外:若左右電梯在同一層,則選擇右側電梯 1. left - call >= right - call print(right) 2. left - call < right - call print(left) Solution --- ``` python def elevator(left, right, call): if abs(left-call) >= abs(right-call): return "right" else: return "left" ``` * 使用 def 關鍵字來定義函數(elevator) * 使用 abs() 函數回傳數字的絕對值 * 用 if、else 條件式執行邏輯運算,比較左側電梯或右側電梯的樓層哪個與呼叫樓層近。 ## 參考資源 :::info * [Kata](https://www.codewars.com/kata/5c374b346a5d0f77af500a5a/javascript) ::: ) * 使用 abs() 函數回傳數字的絕對值 * 用 if、else 條件式執行邏輯運算,比較左側電梯或右側電梯的樓層哪個與呼叫樓層近。 ## 參考資源 :::info * [Kata](https://www.codewars.com/kata/5c374b346a5d0f77af500a5a/javascript) :::