Last active
September 30, 2024 01:18
-
-
Save JadeMin/4c9082f3e33fe3e8d955bf9e9f4f5eb6 to your computer and use it in GitHub Desktop.
Fibonacci with Python
This file contains hidden or 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
| def fibonacci(num: int) -> int: | |
| if num <= 1: return num | |
| prev, current = 0, 1 | |
| for index in range(2, num+1): | |
| next = prev + current | |
| prev, current = current, next | |
| return current | |
| print(fibonacci(33)) |
This file contains hidden or 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
| # 피보나치 수열 함수(F) 정의 | |
| def fibonacci(num: int) -> int: | |
| # F(0)과 F(1)는 항상 인자값과 결과값이 같으므로 그대로 반환한다. | |
| if num <= 1: return num | |
| # 순차적으로 계산하는데 사용될 이전 수와 현재 수 변수를 선언한다. | |
| prev, current = 0, 1 | |
| # F(0), F(1)를 제외한 F(2)부터 함수의 인자값 + 1까지 반복 | |
| # 2 ~ num+1 // 파이썬의 range 함수는 최대값이 제외된 range를 반환하기 때문에 +1한다. | |
| for i in range(2, num+1): | |
| # next 변수에 계산 결과값(이전 수 + 현재 수)을 저장한다. | |
| next = prev + current | |
| # 이전 수, 현재 수를 각각 현재 수, 다음 수로 정의해서 | |
| # 다음 수열 게산을 진행한다. | |
| prev, current = current, next | |
| # for문이 종료됐으면 함수 최상위 블럭에서 current 변수를 반환한다. | |
| return current | |
| # 33번째 피보나치 수열을 출력한다. | |
| print(fibonacci(33)) |
This file contains hidden or 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
| def fibonacci(num: int) -> int: | |
| if num <= 1: return num | |
| return fibonacci(num - 2) + fibonacci(num - 1) | |
| print(fibonacci(33)) |
This file contains hidden or 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
| from functools import cache | |
| @cache | |
| def fibonacci(num: int) -> int: | |
| if num <= 1: return num | |
| return fibonacci(num - 2) + fibonacci(num - 1) | |
| print(fibonacci(33)) |
This file contains hidden or 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
| memo = {} | |
| def fibonacci(num: int) -> int: | |
| if num <= 1: return num | |
| if num not in memo: | |
| memo[num] = fibonacci(num - 2) + fibonacci(num - 1) | |
| return memo[num] | |
| print(fibonacci(33)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment