Kaynağa Gözat

added recursion folder

Harsh Parikh 2 yıl önce
ebeveyn
işleme
85e615cc84

+ 34 - 0
algorithms/recursion/THEORY.md

@@ -0,0 +1,34 @@
+# Recursion
+## Definition:
+- In computer science, recursion is a method of solving a computational problem where the solution depends on solutions to smaller instances of the same problem. [source](https://en.wikipedia.org/wiki/Recursion_(computer_science)#)
+- Most of the modern programming languages allow recursion by allowing the function to call itself within its own code.
+
+## Fundamentals:
+- ### Base Case:
+  - The recursive function must have a base condition to terminate itself or the function shall end up in an infinite loop.
+  - For example
+    ```python
+    def factorial(number):
+        return number * factorial (number - 1)
+    ```
+    - Here, there is no condition to end the recursive call. Hence, the function will run infinitely until the its terminated.
+    
+    - This could be extremely dangerous as a non-terminating recursive program can lead to system crash.
+
+    - Hence, a base case plays an extremely important role for recursive algorithms.
+
+  - An example of a recursive function with a base condition:
+    ```python
+        def factorial(number):
+            if number in (0, 1):
+                return 1
+            else:
+                return number * factorial(number - 1)
+    ```
+    - Here, the function will stop its recursive call when the base condition is reached, hence terminating itself.
+
+- ### Time Complexity: 
+  
+  - Time complexity of recursive algorithms depends on the following factors:
+    1.   Total number of recursive calls
+    1.   Time complexity of additional operations for each recursive call.

+ 18 - 0
algorithms/recursion/factorial.py

@@ -0,0 +1,18 @@
+def factorial(number):
+    """
+    Calculates the factorial of a number using recursion.
+    """
+    assert int(number) == number, "Factorial of decimals not possibe"
+
+    if number < 0:
+        raise ValueError("Factorial of a negative number not possible")
+
+    if number in (0, 1):
+        return 1
+    else:
+        return number * factorial(number - 1)
+
+
+# Driver Code
+if __name__ == "__main__":
+    print(factorial(5))