The Algorithms logoThe Algorithms
About

Python Basics

Python Basic

name = input("what is name ?")
print('HI ' +name)
what is name ?mosh
HI mosh
name = input('what is your birthyear ? ')
year = 2019 -int(name);
print(year)
what is your birthdate ? 2000
19

Type

#type 

print(type(name))
<class 'str'>
weight = input("what is weight ")
final = int(weight)*0.45
print(final)
what is weight 45
20.25
#if want to use this type statement -> year's then we have to use double quotes ""
string = "you're awesome"
print(string)

# if want to assign "important msg" like this we have to use single quote  ''
str = 'im "Hritik"'
print(str)

# for multitline string ''' % ''' for sending mail 

mail = '''
        Hii buddy 

        im Hritik 

        you look awesome 

        thank you,
 '''

print(mail)
you're awesome
im "Hritik"

        Hii buddy 

        im Hritik 

        you look awesome 

        thank you,
 
course = 'python beginners'
print(course[0])
print(course[-2])
print(course[0:])
print(course[:])
print(course[:5])
print(course[0:5])
print(course[1:3]) #exclude 3 only takes 1,2

print(course[1:-1]) # exclude -1 
p
r
python beginners
python beginners
pytho
pytho
yt
ython beginner

Inbuilt - Function

#length of string including space
c = 'hii buddy'
print(len(c))
9
#various function 
msg = 'python is very imp lang'
print(msg.lower())
print(msg.upper())
print(msg.count('i'))
print(msg.find('t'))
print(msg.title())
print(msg.replace('is','are'))
python is very imp lang
PYTHON IS VERY IMP LANG
2
2
Python Is Very Imp Lang
python are very imp lang
#ordering 
# exp > (mul or div) > (add or sub)
exp = 10 + 3*2**2
print(exp)
22

Math function

#Math function
# 1) round
x = 6.5
y = 7.66
print(round(x))
print(round(y))
6
8
# 2) abs -> return positive no.
x = -3.5
print(abs(x))
3.5
# 3) Mathametical function
import math
pi = 3.142
math.cos((60*pi)/180)

# ceil and floor
print(math.ceil(2.9))
print(math.floor(2.9))

#thier are many more maths module
3
2

If - Statement

#if statement

x = 5
y = 10

if (x>y):
    print("truee")
elif (x==y):
    print("falsee")
else:
    print("nothing")
    
print(f"SUM OF X AND Y : {x+y}")
nothing
SUM OF X AND Y : 15

Format

x = "Hii"
y = 'Hritik {}'
z = 'Jaiswal'
print(f"sum of string is x + y : {x+y}")
print(y.format(z))
# we can use 'and' & 'or' in if statement
a=2 
b=3
c=4
if (a<b) and (c>b):
    print('True')
elif (a==b) or (c>a):
    print('Truee')
elif (b>a) and not(b>c):
    print('Trueee')
else:
    print('false')
    
True
#Exercise

weight = int(input('Weight :'))
unit = input('(L)bs or (K)g')
if unit.lower()=='l' or unit.upper()=='L':
    c = weight*0.45;
else:
    c = weight/0.45;
print(c)
Weight :45
(L)bs or (K)gv
100.0

While loop

#while

i=1
while (i<5):
    print('*'*i)
    i+=1
    
*
**
***
****

for loop

#for loop
for item in 'Teacher':
    print(item)
T
e
a
c
h
e
r
for i in ['hii','buddy ','whats','up']:
    print(i)
print('-----------------')
for i in range(4):
    print(i)
print('-----------------')
for i in range(2,8):
    print(i)
print('-----------------')
for i in range(2,8,3):
    print(i)
print('-----------------')
for i in [5,6,7,8]:
    print(i)
hii
buddy 
whats
up
-----------------
0
1
2
3
-----------------
2
3
4
5
6
7
-----------------
2
5
-----------------
5
6
7
8
r = [2,3,4,5]
total = 0
for i in r:
    total+=i
print(total)
print('-----------')
r = [2,3,4,5]
e = sum(r)
print(e)
14
-----------
14
for i in range(4):
    for j in range(3):
        print(f'({i},{j})')
(0,0)
(0,1)
(0,2)
(1,0)
(1,1)
(1,2)
(2,0)
(2,1)
(2,2)
(3,0)
(3,1)
(3,2)
#array
num = [1,2,3,4,5]
for i in num:
    print('$'*i)
$
$$
$$$
$$$$
$$$$$
name = ['ab ','ac','ad','ae']
print(name[0])
print(name[-1])
ab 
ae

List

#2D-List 
matrix = [[1,2,3],[4,5,6],[7,8,9]]
for i in matrix:
    print(i)
print('-----print individual item-----')
for i in matrix:
    for j in i:
        print(j)
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
-----print individual item-----
1
2
3
4
5
6
7
8
9

Inbuilt - Function

#working with function 
# 1.append 2.insert 3.remove 4.pop 5.clear
number = [2,3,4,6]
print('-----Append---------')
number.append(9)
print(number)
print('-----Insert---------')
number.insert(2,8)
print(number)
print('-----Remove---------')
number.remove(8)
print(number)
print('-----pop---------')
number.pop()
print(number)
print('-----clear---------')
number.clear()
print(number)
-----Append---------
[2, 3, 4, 6, 9]
-----Insert---------
[2, 3, 8, 4, 6, 9]
-----Remove---------
[2, 3, 4, 6, 9]
-----pop---------
[2, 3, 4, 6]
-----clear---------
[]
#index 
list_item = [2,4,6,7,2,4]
print(list_item.index(6))
print(list_item.count(2))
2
2
# 1.sort 2.reverse 
item = [3,5,2,8,1]
item.sort()
print(item)
item.reverse()
print(item)
[1, 2, 3, 5, 8]
[8, 5, 3, 2, 1]
#list will update if we changing list item before calling copy function ,
# but list will not be change when u are appending and deleting after copy function
a = [2,3,4,5]
b = a.copy()
a.append(10)
print(b)
[2, 3, 4, 5]
#excercise -> remove a duplicate no. from the list
numbers = [2,3,4,4,3,5]
unique = []

for i in numbers:
    if i not in unique:
        unique.append(i)
        
print(unique)
[2, 3, 4, 5]

tuple

#tuple -> we can not append , remove , pop , insert , u can not modify your list .
#only thing u can do -> count , index a item in list

## The main diffrence between tuple and list is :- tuple is immutable and list is mutable
## that mean we can not change tuple value by modifying it but in list we can do that.
number = (1,2,3)
print(number[0])

# this will throw error :
# number[0] = 5
1

Set

{1,2,3}
{1, 2, 3}
# display unique value 
{1,1,4,2,2,5}
{1, 2, 4, 5}
set([1,2,4,4,8,8,4])
{1, 2, 4, 8}
# add value to the set
s = {1,2,3}
s.add(5)
s
{1, 2, 3, 5}

Map

def times(var):
    return var*2;
    
times(2)
4
seq = [1,2,3]

list(map(times,seq))
[2, 4, 6]

Lambda

# instead of writing like this we can write 
# def times(var):
#     return var*2;

t = lambda var : var*2
t(3)
6
list(map(t,seq))
[2, 4, 6]

Filter

list(map(lambda num : num %2 ==0,seq))
[False, True, False]
list(filter(lambda num : num %2 ==0,seq))
[2]

Unpacking

#unpacking
coordinates = [2,3,4]
# x = coordinates[0]
# y = coordinates[1]
# z = coordinates[2]
# instead of writing like this we can write 
x,y,z = coordinates  #unpacking -> work with both list and tuple
print(x)
2

Dictionaries

#Dictionaries -> contain key - value pairs 

people = {
    "name" :"Hritik Jaiswal",
    "age" : 19,
    "is_male" : True
}
print(people["name"])

# u can not write like -> print(people["Name"])
# we can use GET method to take key-value pair if its not present and display key value pair 
print(people.get("birth","may 31 2000"))
print(people.get("gender"))   #None -> is the object that represent absence of the value

people["name"] = "HritiK Dinesh Jaiswal"  # modify name
print(people.get("name"))
Hritik Jaiswal
may 31 2000
None
HritiK Dinesh Jaiswal
#excersice -> inuput 1234 display output : one two three four
phone =  input("phone : ")

dict  = {
    "1" :"One",
    "2":"Two",
    "3" :"Three",
    "4" :"Four",
    "5" :"Five",
    "6" :"Six",
    "7" :"Seven",
    "8" :"Eight",
    "9" :"Nine",
    "0" :"zero",
}
output = "" 
for i in phone:
    
    output += (dict.get(i,"?")) + " " 
    print(i)
print(output) 
phone : 105
1
0
5
One zero Five 
#excerisce -> opposite 
words = ["one", "two","three","four","five","six", "seven","eight","nine","zero"]

word = input("Enter the word : ")
mapping  = {
    "one":"1", 
    "two":"2",
    "three":"3",
    "four":"4",
    "five":"5",
    "six":"6", 
    "seven":"7",
    "eight":"8",
    "nine":"9",
    "zero":"0"
}
spliting = word.split()
print(spliting)
for i in spliting:
    print(mapping.get(i,"&"))
    
    
Enter the word : one seven two
['one', 'seven', 'two']
1
7
2
#excersice -> print emoji
message = input(">")
words= message.split()
emoji = {
    ":)" :"😄",
    ":(" :"😔"
}
output = ""
for i in words:
    output += emoji.get(i,i) + " "
    
print(output)
>good morning :)
good morning 😄 

Function

#function
def text():
    print("im hritik")
print("hii")
text()
hii
im hritik

Parameter and Arguments

#function with parameter
#parameter ->is placeholder that we passed to the function
#argumetnt -> is actual value that u gone pass inside function
def text(f_name, l_name):
    print(f'Hii {f_name} and {l_name}')
print("thanks")
text('hritik','jaiswal')
thanks
Hii hritik and jaiswal

keyword argument

#keyword argument -> its helpful when u don't want to pass argument in order u can pass in any order 
def text(discount , shipping ,total ):
    print(f'Here total is {total} including shipping charges {shipping} + discount {discount}')
print("hello")
text(shipping=2000,total=5000,discount=500)
hello
Here total is 5000 including shipping charges 2000 + discount 500
#return statement 
def square(num):
    return num*num
result = square(5)
print(result)
    
25
#tric -> if u don't write return statement then it will return object which is : none 
def cube(n):
    print(n**3)
print(cube(3))
27
None

Exception

#exception -> when we try to input string value instead of int 
# age = int(input("your age"))
# print(age)

try:
    age = int(input("your age : "))
    print(age)
except ValueError:
    print('invalid value')
your age : twenty
invalid value

try:
    age = int(input("your age : "))
    income = 20000
    risk = float(income/age);
    print(f'risk is {risk}')
except ValueError and ZeroDivisionError:
    print("invalid value or age can't be negative ")
your age : 0
invalid value or age can't be negative 

Class

#class 
# 1) type -1

class rect:
    def rect_area(self):
        print("area")
p = rect()
p.rect_area()

area
# 2) type -2
class Employee:
    def __init__(self, first, last , salary):
        self.first = first
        self.last = last
        self.salary = salary
        self.email = first + '.'+last +'@gmail.com'
    
    def fullname(self):
        return "{} {}".format(self.first,self.last)

emp1 = Employee('Hritik','Jaiswal',5000)
emp2 = Employee('Aniket','Jaiswal',6000)

#their are two methods 
print(emp1.fullname())
print(Employee.fullname(emp1))
              
Hritik Jaiswal
Hritik Jaiswal
# 3) type -3
class Point:
    def __init__(self,a,l,h):
        self.a = a
        self.l = l
        self.h = h
        
    def square(self):
        print(f"area of square :{self.a*self.a}")
    
    def rectangle(self):
        print("area of rectangle is : {}".format(self.l*self.h))
    

#create a object 
point1 = Point(3,2,3)
point1.square()
point1.rectangle()
area of square :9
area of rectangle is : 6

Inheritance

#inheritance -> dog and cat are inherite a class mammel
class mammel:
    def walk(self):
        print("walk")

class dog(mammel):
    def bark(self):
        print("bark")

class cat(mammel):
    pass

dog1 = dog()
dog1.bark()

cat1 = cat()
cat1.walk()
bark
walk

Module

#module -> module.ipynb file which we have created we can directly import function also
#we need to install from anaconda prompt -> pip install import-ipynb
import import_ipynb

import module
from module import cm2m

cm2m(100)
m2cm
1.0
numbers = [5,4,6,8,10]
print(max(numbers))
print(min(numbers))
10
4

Packages

package -: we can create a seperate .py file and extract this file and import into another file as similar to module

package is collections of different modules

Type of Module

    1) Absolute module 

from mypackage.mymodule1 import class A obj = class A

    2) relative module

if im working in "module1" & i want to import Class C from "module2" into my "module1"

from module2 import classC obj = classC()

Random

import random

for i in range(3):
    print(random.random())
0.8556515733440572
0.9018671283206765
0.6655666651378818
for i in range(3):
    print(random.randint(10,20))
12
20
15
# randomly choose the value 
members = ['hritik', 'jaiswal','aniket','shweta']
show = random.choice(members)
print(show)
jaiswal
#excercise -> dice thrown give random value

class Dice:
    def roll(self):
        x = (1,2,3,4,5,6)
        y = (1,2,3,4,5,6)
        m = random.choice(x)
        l = random.choice(y)
        print("({},{})".format(m,l))
        

r = Dice()
r.roll()

(2,4)
# another method

class Dice:
    def roll(self):
        first = random.randint(1,6)
        second = random.randint(1,6)
        return first,second
dice = Dice()
print(dice.roll())
(5, 6)

Files and Directories

from pathlib import Path
path = Path(".")
print(path.exists())


#if u want to make new directory

# path1 = Path("Files_Directories")
# path1.mkdir()

#when u want to remove directory
#path.rmdir()

True
path2 = Path()
for file in path2.glob("*.ipynb"):
    print(file)
ch02.ipynb
module.ipynb
Python-1.ipynb
path3 = Path()
for file in path3.glob("*"):
    print(file)
.ipynb_checkpoints
ch02.ipynb
Files_Directories
module.ipynb
Python-1.ipynb

Working with spreadsheet

import openpyxl as xl
from openpyxl.chart import BarChart,Reference

# Here openpyxl -> package , chart -> module , BarChart -> class
#instead of passing a file name ->  we can use function and store the path in "filename" variable and pass as argument to function 

wb = xl.load_workbook(r'C:\Users\Hritik Jaiswal\Downloads\Spreadsheet\transactions.xlsx')
sheet = wb['Sheet1']


#method to get a cell 

cell = sheet['a1']
#another method ->   cell = sheet.cell(1,1)

print(cell.value)
#print max row
print(sheet.max_row)
transaction_id
4
#we have to modify value of the cell and store into another excel file

for row in range(2,sheet.max_row+1):
    cell = sheet.cell(row,3)  # column is 3
    print(cell.value)
    corrected_value = cell.value * 0.9
    
    #now we have to place a corrected value into anther column 
    corrected_value_cell = sheet.cell(row,4)  #add corrected value into the 4 column
    
    corrected_value_cell.value = corrected_value
#Excersice 

# u have to create a bar graph in excel


values = Reference(sheet, 
          
          min_row=2,max_row = sheet.max_row,
         
          min_col = 4 , max_col = 4
         )

chart = BarChart()
chart.add_data(values)
sheet.add_chart(chart, 'f2')


wb.save("transaction2.xlsx")

5.95
6.95
7.95

Machine learning

Steps :

                1) Import the Data 
                2) clean the Data
                3) split the Data into training/test sets
                4) create a model
                5) train the model
                6) make prediction
                7) Evaluate and Improve
#Importing a data set
import pandas as pd
df = pd.read_csv('vgsales.csv')
df.shape
(16598, 11)
df.describe()
Rank Year NA_Sales EU_Sales JP_Sales Other_Sales Global_Sales
count 16598.000000 16327.000000 16598.000000 16598.000000 16598.000000 16598.000000 16598.000000
mean 8300.605254 2006.406443 0.264667 0.146652 0.077782 0.048063 0.537441
std 4791.853933 5.828981 0.816683 0.505351 0.309291 0.188588 1.555028
min 1.000000 1980.000000 0.000000 0.000000 0.000000 0.000000 0.010000
25% 4151.250000 2003.000000 0.000000 0.000000 0.000000 0.000000 0.060000
50% 8300.500000 2007.000000 0.080000 0.020000 0.000000 0.010000 0.170000
75% 12449.750000 2010.000000 0.240000 0.110000 0.040000 0.040000 0.470000
max 16600.000000 2020.000000 41.490000 29.020000 10.220000 10.570000 82.740000
df.values
array([[1, 'Wii Sports', 'Wii', ..., 3.77, 8.46, 82.74],
       [2, 'Super Mario Bros.', 'NES', ..., 6.81, 0.77, 40.24],
       [3, 'Mario Kart Wii', 'Wii', ..., 3.79, 3.31, 35.82],
       ...,
       [16598, 'SCORE International Baja 1000: The Official Game', 'PS2',
        ..., 0.0, 0.0, 0.01],
       [16599, 'Know How 2', 'DS', ..., 0.0, 0.0, 0.01],
       [16600, 'Spirits & Spells', 'GBA', ..., 0.0, 0.0, 0.01]],
      dtype=object)

Shortcut

we can use shift-tab to describe function

all shortcut is present when we click 'h' in editor

Real world problem

recommend various music albums thier likely to buy based on age and gender

Importing Data

import pandas as pd

data = pd.read_csv('music.csv')
data
age gender genre
0 20 1 HipHop
1 23 1 HipHop
2 25 1 HipHop
3 26 1 Jazz
4 29 1 Jazz
5 30 1 Jazz
6 31 1 Classical
7 33 1 Classical
8 37 1 Classical
9 20 0 Dance
10 21 0 Dance
11 25 0 Dance
12 26 0 Acoustic
13 27 0 Acoustic
14 30 0 Acoustic
15 31 0 Classical
16 34 0 Classical
17 35 0 Classical
data.describe()
age gender
count 18.000000 18.000000
mean 27.944444 0.500000
std 5.127460 0.514496
min 20.000000 0.000000
25% 25.000000 0.000000
50% 28.000000 0.500000
75% 31.000000 1.000000
max 37.000000 1.000000
# we will create two input data set that will be 'age' and 'gender'
# we will pass 'age' and 'gender' and based on the input we predict the output 
# output will be stored in 'genre' 

X = data.drop(columns=['genre'])

Y = data['genre']

Learning and Predicting

from sklearn.tree import DecisionTreeClassifier

model = DecisionTreeClassifier()
# takes two attributes 1. input dataset 2. output dataset
model.fit(X,Y)


#let make a prediction by passing input Here 22 is age and 0 is female

prediction = model.predict([[22,0],[25,1]])
prediction

array(['Dance', 'HipHop'], dtype=object)

Calculating the Accuracy

# for calculating the accuracy we need to test and train the model 
# generally 70-80% data need to training and 20-30% for testing

from sklearn.model_selection import train_test_split 

# Here we use 20% for testing and check with respect to the predicted value
# the function will return 4 tuple we have to get that result into a variable 

X_train,X_test,Y_train,Y_test = train_test_split(X,Y,test_size = 0.5)
print(X_train)
model.fit(X_train,Y_train)

# we pass input as X_test in attribute
prediction = model.predict(X_test)

# now to check accurancy we have to compair the prediction with y_test()
from sklearn.metrics import accuracy_score

score = accuracy_score(Y_test,prediction)
print("Accuracy is : {}".format(score))

#every time we run are model accuracy will be changing
    age  gender
0    20       1
3    26       1
5    30       1
6    31       1
12   26       0
9    20       0
11   25       0
2    25       1
10   21       0
Accuracy is : 0.6666666666666666

Model Persistance

for training model again again takes lot of time instead we can save the trained model in one joblib file

run these piece of code after applying model i.e after :

    model = DecisionTreeClassifier()
    
    from sklearn.externals import joblib 
    joblib.dump(model,'model-recommender.joblib')

after runing these commment the trained model syntax and and then direclty load

    joblib.load('model-recommender.joblib')

Visualizing a Decision Tree

# u can see a graph i.e decision tree on visual studio code 
# by clicking a sidebar preview button
    
from sklearn import tree
tree.export_graphviz(model,
                    out_file = "music-recommender.dot",
                    class_names = sorted(Y.unique()),
                    label = 'all',
                    rounded =True ,
                    filled= True
                    )