Python Functions and Classes

Sometimes you need to define your own functions to work with custom data or solve some problems. A function can be defined with a prefix def. A class is like an umbrella that can contains many data types and functions, it is defined by class prefix.

Functions


In [1]:
def hello(a,b):
    return a+b

In [2]:
# Lazy definition of function
hello(1,1)


Out[2]:
2

In [3]:
hello('a','b')


Out[3]:
'ab'

Class

Class is a blueprint defining the charactaristics and behaviors of an object.

class MyClass:
    ...
    ...

For a simple class, one shall define an instance

__init__()

to handle variable when it created. Let's try the following example:


In [4]:
class Person:
    def __init__(self,age,salary):
        self.age = age
        self.salary = salary
    def out(self):
        print(self.age)
        print(self.salary)

This is a basic class definition, the age and salary are needed when creating this object. The new class can be invoked like this:


In [5]:
a = Person(30,10000)
a.out()


30
10000

The __init__ initilaze the variables stored in the class. When they are called inside the class, we should add a self. in front of the variable. The out(Self) method are arbitary functions that can be used by calling Yourclass.yourfunction(). The input to the functions can be added after the self input.

Python Conditionals And Loops

The for statement

The for statement reads

for xxx in yyyy:

yyyy shall be an iteratable, i.e. tuple or list or sth that can be iterate. After this line, user should add an indentation at the start of next line, either by space or tab.

Conditionals

A conditional statement is a programming concept that describes whether a region of code runs based on if a condition is true or false. The keywords involved in conditional statements are if, and optionally elif and else.


In [6]:
# make a list
students = ['boy', 'boy', 'girl', 'boy', 'girl', 'girl', 'boy', 'boy', 'girl', 'girl', 'boy', 'boy']

boys = 0; girls = 0

for s in students:
    if s == 'boy':
        boys = boys +1
    else:
        girls+=1
        
print("boys:", boys)
print("girls:", girls)


boys: 7
girls: 5

The While statement

The While statement reads

while CONDITIONAL:

CONDITIONAL is a conditional statement, like i < 100 or a boolean variable. After this line, user should add an indentation at the start of next line, either by space or tab.


In [7]:
def int_sum(n):
    s=0; i=1
    while i < n:
        s += i*i
        i += 1
    return s
int_sum(1000)


Out[7]:
332833500

Performance


In [8]:
%timeit int_sum(100000)


11 ms ± 195 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Numba translates Python functions to optimized machine code at runtime using the LLVM compiler library. Your functions will be translated to c-code during declarations. To install numba,

pip install numba

In [9]:
import numba

In [10]:
@numba.njit
def int_sum_nb(n):
    s=0; i=1
    while i < n:
        s += i*i
        i += 1
    return s
int_sum_nb(1000)


Out[10]:
332833500

In [11]:
%timeit int_sum_nb(100000)


180 ns ± 4.04 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

Examples


In [12]:
import random
def monte_carlo_pi(n):
    acc = 0
    for i in range(n):
        x = random.random()
        y = random.random()
        if (x**2 + y**2) < 1.0:
            acc += 1
    return 4.0 * acc / n

In [13]:
monte_carlo_pi(1000000)


Out[13]:
3.144108

In [14]:
%timeit monte_carlo_pi(1000000)


324 ms ± 4.35 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [15]:
@numba.njit
def monte_carlo_pi_nb(n):
    acc = 0
    for i in range(n):
        x = random.random()
        y = random.random()
        if (x**2 + y**2) < 1.0:
            acc += 1
    return 4.0 * acc / n

In [16]:
monte_carlo_pi_nb(1000000)


Out[16]:
3.139924

In [17]:
%timeit monte_carlo_pi_nb(1000000)


9.06 ms ± 309 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [18]:
@numba.njit
def monte_carlo_pi_nbmt(n):
    acc = 0
    for i in numba.prange(n):
        x = random.random()
        y = random.random()
        if (x**2 + y**2) < 1.0:
            acc += 1
    return 4.0 * acc / n

In [19]:
monte_carlo_pi_nbmt(1000000)


Out[19]:
3.139348

In [20]:
%timeit monte_carlo_pi_nbmt(1000000)


8.82 ms ± 101 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Summary

Python loops and recursive are not recommended because it needs a lot of system overhead to produce a function calls and check typing. But new tools are avaliable to convert these codes into high performance code.


In [ ]: