In [1]:
def hello(a,b):
return a+b
In [2]:
# Lazy definition of function
hello(1,1)
Out[2]:
In [3]:
hello('a','b')
Out[3]:
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()
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.
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)
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]:
In [8]:
%timeit int_sum(100000)
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]:
In [11]:
%timeit int_sum_nb(100000)
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]:
In [14]:
%timeit monte_carlo_pi(1000000)
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]:
In [17]:
%timeit monte_carlo_pi_nb(1000000)
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]:
In [20]:
%timeit monte_carlo_pi_nbmt(1000000)
In [ ]: