Modules

 import module_name as alias

For calling : module_name.func_name(arguments)

Or

from module_name import func1,func3 (or*) 

For calling :

func1(arguments) 

func2(arguments) (Name Error) 

dir(module_name) - describe all classes, functions and variables 

Some default magic classes - builtins, cached, doc, file, loader, name, package, spec

Note:Whenever a module is used in a program, its compiled file will be generated and stored in the hard disk permanently 

Note: Custom made modules need to be in same folder as program or in default python path and this gets stored in variable PYTHONPATH

While searching for modules when an import statement is used first preference is given to the folder the program is present in then python path and if not found even after that then an error. 

LEGB Rule: Local, Enclosing, Global, Built-in 

For passing arguments in a function in an indefinite order :

Func1(arg2=value, arg1=val, arg3=val...) 

A function can return multiple value which be later picked up by a variable as tuple

Common built-in functions:

Round(Number, no. of decimal to be rounded off) 

Round(12.5)==12

Round(13.5)==14

if the second argument is in negative then it will start round off the tens, hundreds position and so on. 

abs(number) - Returns absolute value as int ot float as per input 

help(function/module) eg. print(help(math.cos)) 

max, min - If two same values then they would return the one which has lowest positive index

Sum() 

any(iterable) - Returns True if even one element in iterable is True or non-zero 

all(iterable) - Returns True if all elements in the iterable are True or non-zero 

SYS

Used to see and even update the default path of python 

Sys. Path - shows path

Sys.path.append("new path") - adds a new path to default path list

Sys. Exit

Sys. Version 

MATH:

ceil(number)==lower value

floor(number)==upper value

pow(a,b)==a**b

pow(a, b, c) == (a**b) % c

sqrt(number)-value error if number is negative 

fabs(number)==absolute value

log10(number)

sin(number)

tan(number)

Note: Most math module functions except ceil and floor return value as float

RANDOM:

randrange(lowerlimit,upperlimit)==generates integer between the two limits,default lower=0 [l<=ans<h]

random(empty)==random value between 0-1 including zero ,excluding 1

randint(lowerlimit,upperlimit)==[l<=ans<=h]

uniform(l,h)==returns floating value as ans , l<=ans<h

choice(sequence)== a random selection of indexed value from a sequence

shuffle(sequence)== shuffles the contents of the sequence in place

To get a random num between a and b with b>a use- 

(b-a) *random.random()+a

STATISTICS

mean([list])

median([list])

mode([list])

If more than one value is eligible for mode then that value is returned as output which occur at earliest from index 0

Eg.[1,2,3,1,2,3] Mode output will be 1

DATETIME:

usage eg datetime.date.today()

Python support yyyy-mm-dd format

Functions under .date class:

today()

.year , .date , .month - returns only the corresponding value from yyyy-mm-dd format

Functions under .time class:

.now()

.hour , .minute , .second -  returns only the corresponding value from hh-mm-ss... format

BISECT:

import bisect

Tip: Sort list before using bisect

bisect.bisect(list,number)==returns where(index) should number be inserted so that the list remain sorted

bisect.insort(list,number)==automatically insert number in list(update original list)


ITERTOOLS

c=list(zip(iter1,iter2))
zip returns a list of tuples with 1 corresponding element from each iterable object
a=iter(iter1)
print(next(a))
import itertools
infinite iterators :
.count(start,step)
.cycle(iter1)
.repeat(value,no.of times to repeat)

combinatoric iterators:
from itertools import func_name
list(product(iter1,iter2,repeat=no. of times a value can be taken))
the above create all possible combination of elements in restriction of repeat

list(permutations(iter1,group_size))
list(combinations(iter1,group_size))
list(combinations_with_replacement(iter1,group_size)) //combination in sorted order

terminating iterators:
import itertools
accumulate(iter,func) if not defined addition is default func
this creates an iterable object with func operation performed on two successive elements

chain(iter1,iter2..) creates an iterable object by joining elements  of iter1,iter2...

dropwhile(func/condition,iter1)
start printing elements of iter1 after condition returns the first false

filterfalse(condition,iter1)
checks for condition and print element only if it returns false 

islice(iter1,start,stop,step)
slice an iterable object in a certain way 

starmap(func,list_of_tuples)
perform a function in those tuples and returns output for each of them

takewhile(condition,iter1)
return value till first false result of element of iteration

tee(iter1,count/n)
create n copies of iter1 as an list of iterable object
y=iter(l1)
x=i.tee(y,3)
print(list(x[0]))

zip_longest(iter1,iter2,fillval="")
returns a list of tuples with 1 corresponding element from each iterable object with the empty values replaced with 'fillval'

assert condition , "error message"
continue the execution of code only if condition is true else error is thrown

// gives assertion error or == "error message" 

return a + \
        b
// the outbut will be a+b as '\' mark change in line
NUMPY and PANDAS
NUMPY AS NP
variable=np.array([element 1,element2,element3])==creates a single dimension matrix
variable=np.array([[element1,element2],[element3,element4]])==2d matrix
variable=np.arange(start,end)==eg 5,8 ==[5 6 7]
variable can be multiplied or added with constant to add/multipy each of its element
array with random numbers: 
var=np.random.randint(low=50, high=101, size=(6,5))
5=no. of columns
6=no.of rows

v=np.zeros(n)==create an array of n element all zeroes of float type
v=np.ones(n)==create an array of n element all ones of float type
v=np.empty(n)==create an array of n element all empty of float type
print(v.shape)==output is of form (a1,a2) where a1 is number of elements and a2 =0 if horizontal,1 if vertical
v.shape=(n,1)
v=np.linspace(a,b,c)== from a to be (float) with five elements (all equal arranged with 1st element as a and last as b)
simple slicing v[1],v[:1] , v[row,column]etc

print(
np.sin(nparray)
np.sum(nparray)
np.prod(nparray)
np.mean(nparray)
np.std(nparray)// standard deviation
np.var(nparray)//variance
np.min(nparray)
np.max(nparray)
np.argmin(nparray)//index of minimum
np.argmax(nparray)//index of maximum
)
v>3
craetes an array of true and false values
v(v>3)==creates an array where condition hold true
v(v>3,replace values which hold true,replace valuse which don't hold true)
v1+v2
v2+30 // added to each element
v1*v2
v1*10
v1 @ v2 // dot product
v1[:,:,0].T // transpose 
np.sort(v1)

NUMPY AS NP
variable=np.array([element 1,element2,element3])==creates a single dimension matrix
variable=np.array([[element1,element2],[element3,element4]])==2d matrix
variable=np.arange(start,end)==eg 5,8 ==[5 6 7]
variable can be multiplied or added with constant to add/multipy each of its element
array with random numbers: 
var=np.random.randint(low=50, high=101, size=(6,5))
5=no. of columns
6=no.of rows

PANDAS AS PD 
variable_pd=pd.DataFrame(data="data_variable",index=[01,2,3,4,5],columns="list with column headings")
output = index column data
to create new column:
variable_pd["new column name"]=values eg. variable_pd["existiong column"]+2
extracting specific data from DataFrame:
1.column variable_pd["column name"] print as:: 
Column 'column name'
index data
Name: column name,dtype: data_type
2.rows till row number '3':
variable_pd.head(4) print row 0,1,2,3
3.specific range of rows:eg 2,3,4
variable_pd[2:5]
4.certain single row:
variable_pd.iloc[[row number]]
5.single cell
variable_pd.at[row/index,column]
or
variable_pd.loc[row/index].at[column]
or
variable_pd[column][row/index]
New DataFrame:
new_variable=variable_pd.copy()

Other useful modules:
Webbrowser
Timeit
Requests
english-words
random-word
pathlib

Comments

Popular posts from this blog

Dictionary and Sets in Python

Insertion Sort in python

Grid Printing Code for Python