규도자 개발 블로그
[해커랭크(Hackerrank)/30 Days of Code/파이썬3(python3)] Day 9: Recursion 3 본문
[해커랭크(Hackerrank)/30 Days of Code/파이썬3(python3)] Day 9: Recursion 3
규도자 (gyudoza) 2019. 3. 21. 21:08Objective
Today, we're learning and practicing an algorithmic concept called Recursion. Check out the Tutorial tab for learning materials and an instructional video!
Recursive Method for Calculating Factorial
Task
Write a factorial function that takes a positive integer, as a parameter and prints the result of ( factorial).
Note: If you fail to use recursion or fail to name your recursive function factorial or Factorial, you will get a score of .
Input Format
A single integer, (the argument to pass to factorial).
Constraints
- Your submission must contain a recursive function named factorial.
Output Format
Print a single integer denoting .
Sample Input
3
Sample Output
6
Explanation
Consider the following steps:
From steps and , we can say ; then when we apply the value from to step , we get . Thus, we print as our answer.
풀이
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the factorial function below.
def factorial(n):
return 1 if n == 1 else n * factorial(n - 1)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
result = factorial(n)
fptr.write(str(result) + '\n')
fptr.close()
설명
처음 보면 멘붕을 야기하는 재귀형 함수 문제이다. 처음 봤을 때는 재귀함수를 잘 이해하기 힘든데 조건문이 끝나기 전까지 값을 대입시키지 않은 채로 반환값들을 쭉 나열해놓은 다음에 주어진 연산을 수행하면 조금 이해하기 쉽다.
'알고리즘 > 풀이' 카테고리의 다른 글
[백준/9012/파이썬(python3)] 괄호 (0) | 2019.03.22 |
---|---|
[해커랭크(Hackerrank)/30 Days of Code/파이썬3(python3)] Day 10: Binary Numbers (0) | 2019.03.21 |
[해커랭크(Hackerrank)/30 Days of Code/파이썬3(python3)] Day 8: Dictionaries and Maps (0) | 2019.03.21 |
[해커랭크(Hackerrank)/30 Days of Code/파이썬3(python3)] Day 7: Arrays (0) | 2019.03.21 |
[해커랭크(Hackerrank)/30 Days of Code/파이썬3(python3)] Day 6: Let's Review (0) | 2019.03.21 |