汪群超 Chun-Chao Wang

Dept. of Statistics, National Taipei University, Taiwan

Appendix A: Python functions: def

範例 1: Syntax and Usage

def f1(arg1, arg2, arg3):
    return arg1 + arg2 + arg3

def f2(arg1, arg2, arg3, Sum=True):
    # Calculate the sum; calcSum is optional with default=True
    if Sum:
        return arg1 + arg2 + arg3
    # Calculate the average instead
    else:
        return (arg1 + arg2 + arg3) / 3

print(f1(1, 2, 3))
print(f2(1, 2, 3)) # use default value for calcSum
print(f2(1, 2, 3, Sum=False))
# Avg = f2(3, 10, Sum = False) # wrong syntax
# Avg = f2(3, 10, Sum = False, arg3 = 1) # correct syntax

Note

  1. A function has two kinds of arguments: positional (arg1, arg2, arg3) and key/value paired (Sum = True).

範例 2: Syntax and Usage

def lessThan(cutoffVal, *vals) : # * means any other positional parameters.
    ''' Return a list of values less than the cutoff. ''' # Python document
    arr = []
    for val in vals :
        if val < cutoffVal:
            arr.append(val)
    return arr

print(lessThan(10, 2, 17, -3, 42, 5))

Note

  1. The argument leading with * means any other positional parameters.
  2. Learn the method append to expand a list from empty.
  3. The reader can try to add more numbers to be the arguments and see what happens.

範例 3: Application



Create a function that computes a few basic descriptive statistics of a random sample.
import numpy as np
import scipy.stats as sp


def desc_stats(x):
    mean = x.mean()
    std = x.std()
    skew = sp.skew(x)
    kurt = sp.kurtosis(x)
    return mean, std, skew, kurt


x = np.random.normal(size=100)
mu, s, sk, ku = desc_stats(x)
print(
    "For normal samples \n mean = {:.4f}, std = {:.4f}, skewness = {:.4f}, kurtosis = {:.4f}".format(
        mu, s, sk, ku
    )
)
x = np.random.chisquare(df=2, size=100)
mu, s, sk, ku = desc_stats(x)
print(
    "For Chi2 samples \n mean = {:.4f}, std = {:.4f}, skewness = {:.4f}, kurtosis = {:.4f}".format(
        mu, s, sk, ku
    )
)

Note

  1. The reader may want to add more statistics in the def function.

練習: Application


The curve length of a function $f(x)$ starts from x=a is given by

L(x) = \int_a^x \sqrt{1 + (f'(t))^2}\; dt

The objective is to draw the graph of L(x) (see the graph below). Please write a def function to compute L(x) with three arguments (f, a, b) that denote the function, lower and upper bounds, respectively. Let f(x)=x^2/2 and a=0.