Python における再帰的な階乗の計算

PythonPythonBeginner
今すぐ練習

This tutorial is from open-source community. Access the source code

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

数学において、非負整数 n の階乗は n! で表され、n 以下のすべての正整数の積です。たとえば、5! = 5 x 4 x 3 x 2 x 1 = 120 です。このチャレンジでは、再帰を使って与えられた数の階乗を計算する Python 関数を書きます。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/ErrorandExceptionHandlingGroup(["Error and Exception Handling"]) python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python/BasicConceptsGroup -.-> python/comments("Comments") python/ControlFlowGroup -.-> python/conditional_statements("Conditional Statements") python/FunctionsGroup -.-> python/function_definition("Function Definition") python/ErrorandExceptionHandlingGroup -.-> python/raising_exceptions("Raising Exceptions") subgraph Lab Skills python/comments -.-> lab-13628{{"Python における再帰的な階乗の計算"}} python/conditional_statements -.-> lab-13628{{"Python における再帰的な階乗の計算"}} python/function_definition -.-> lab-13628{{"Python における再帰的な階乗の計算"}} python/raising_exceptions -.-> lab-13628{{"Python における再帰的な階乗の計算"}} end

階乗

非負整数 num を引数として受け取り、その階乗を返す関数 factorial(num) を書きます。この関数は再帰を使って階乗を計算する必要があります。num1 以下の場合、1 を返します。それ以外の場合、numnum - 1 の階乗の積を返します。num が負または浮動小数点数の場合、関数は例外を投げる必要があります。

def factorial(num):
  if not ((num >= 0) and (num % 1 == 0)):
    raise Exception("Number can't be floating point or negative.")
  return 1 if num == 0 else num * factorial(num - 1)
factorial(6) ## 720

まとめ

このチャレンジでは、再帰を使って数の階乗を計算する方法を学びました。また、Python で例外を処理する方法も学びました。