Python

Python3

Installation

Ubuntu
apt install python3
AlmaLinux
dnf install python3{minor-version}
Arch Linux
pacman -S python

Examples

Fibonacci Numbers
# -*- coding: utf-8 -*-
# Fibonacci Numbers by Python3

import sys

def fib(n):
    if n < 2 :
        return n
    else:
        return fib(n-2) + fib(n-1)

argv = int(sys.argv[1])

print(fib(argv))

"""
example
    run:
        python fibonacci.py 39
"""

Memoization

# -*- coding: utf-8 -*-
# Fibonacci Numbers by Python3

import sys

r = {0:0,1:1,2:1}

def fib(n):
    global r
    try:
        return r[n]
    except:
        r[n] = fib(n - 2) + fib(n - 1)
        return r[n]


argv = int(sys.argv[1])

print(fib(argv))

"""
example
    run:
        python fib_memo.py 39
"""

Binet's formula

# -*- coding: utf-8 -*-
# Fibonacci Numbers by Python3

import sys
import math

def fib(n):
    return math.floor(((1 + math.sqrt(5)) / 2) ** n / math.sqrt(5) + 0.5)


argv = int(sys.argv[1])

print(fib(argv))

"""
example
    run:
        python fib_golden.py 39
"""

Matrix form

# -*- coding: utf-8 -*-
# Fibonacci Numbers by Python3

import sys
import numpy as np

def fib(n):
    return np.linalg.matrix_power(np.array([[1, 1], [1, 0]]), n)[0][1]


argv = int(sys.argv[1])

print(fib(argv))

"""
example
    run:
        python fib_array.py 39
"""