Here are the steps to solve this problem:
1. Convert both lists of numbers to sets:
set1 = {11, 2, 3, 4, 15, 6, 7, 8, 9, 10}
set2 = {15, 2, 3, 4, 15, 6}
2. Find the intersection of the two sets:
intersection = set1.intersection(set2)
3. The number of elements in the intersection is the number of similar elements:
similarity = len(intersection)
4. Print the result:
print(similarity)
The similarity between the two sets is 4, since they both contain the elements {2, 3, 4, 15}.
2. COURSE OUTLINE
Installing and Using Python
Basic I/O
Variables and Expressions
Conditional Code
Functions
Loops and Iteration
Python Data Structures
Errors and Exceptions
Object Oriented with Python
Multithreaded Programming with Python
Install/Create and Using Python Library
Compile Python Script
Resources
15. VARIABLES AND EXPRESSIONS
> pi = pi + 1
> number += 1
> text = text + “haha”
> n = 2 + 2 * 2 - 5
n ?
Dynamics Variable
Expression
> a = 1
> a = “1”
> a = 1.0
> a = f()
18. VARIABLES AND EXPRESSIONS
Quiz Time “ Let me introduce myself “
FRIST NAME:
LAST NAME:
AGE:
GENDER:
TEL:
WEIGHT (KG.):
HEIGHT (CM.) :
MY NAME IS ________________.
I AM _________ YEARS OLD.
I AM A _________.
MY PHONE NO. IS ______________.
MY WEIGHT IS ________________KG. (~_________ LB.)
MY HEIGHT IS ________________CM. (~__________M.)
Input:
Output:
10 Min. Q1
*1 kg = 2.205 lb
20. CONDITIONAL CODE
Syntax
if <condition> :
statment(s)
elif <condition> :
statment(s)
else :
statment(s)
Comparators
> , < , >= , <=, not, !=
Operators
A & B , A and B
A | B , A or B
Syntax
short if
x = <true> if <condition> else <false>
21. CONDITIONAL CODE
Example
if (5 > 10) | (10 > 15) & ( 1 != 1) :
print(False)
elif (10 > 5) & (not(False)):
print(True)
else:
print(NULL)
Example (short if)
x = 5 if 5 > 10 else 10
22. CONDITIONAL CODE
Quiz Time “ What is my BMI level ?“
FRIST NAME:
LAST NAME:
AGE:
GENDER:
TEL:
WEIGHT (KG.):
HEIGHT (CM.) :
MY NAME IS ________________.
I AM _________ YEARS OLD.
I AM A _________.
MY PHONE NO. IS ______________.
MY WEIGHT IS ________________KG. (~_________ LB.)
MY HEIGHT IS ________________CM. (~__________M.)
MY BMI IS : __________________.
Input:
Output:
5 Min. Q2
*1 kg ~ 2.205 lb
25. LOOPS AND ITERATION
enumerate
#generate index i start from 0
for i, n in enumerate(<iterator object>):
statement(s)
Example
for i, n in enumerate(range(0,10,5)):
pow = n ** i
print(pow)
1
5
26. LOOPS AND ITERATION
Syntax
for…
for n in <iterator object>:
statement(s)
while..
while(<conditions>):
statement(s)
Examples
for…
for n in range(10):
print(n ** n)
while..
while(True):
break
for n in <iterator object>:
for n in <iterator object>:
…….
27. LOOPS AND ITERATION
break
#exit loop
for n in <iterator object>:
break
continue
#next loop
for n in <iterator object>:
continue
pass
#pass
while True
pass
28. LOOPS AND ITERATION
Syntax
for…
for n in <iterator object>:
statement(s)
while..
while(<conditions>):
statement(s)
range
#generate index number
range(5) ==> [0,1,2,3,4]
range(0,10,2) ==> [0,2,4,6,8]
enumerate
#generate index i start from 0
for i, n in enumerate(<iterator object>):
statement(s)
break
#exit loop
for n in <iterator object>:
break
continue
#next loop
for n in <iterator object>:
continue
31. FUNCTIONS
Argument
def <function name>(x, y) :
statement(s)
Argument : Default value
def foo(x = 1, y = 2) :
statement(s)
Call function and parse values
fn(3,2) #args
fn(x = 2, y = 1) #kwargs
Argument : *args, **kwargs
def fn(x = 1, y = 2, *args)
def fn(x = 1, y = 1, **kwargs)
def fn(x = 1, y = 1,*args, **kwargs)
32. FUNCTIONS
Return
def <function name>(x, y) :
statement(s)
return value
Return
def <function name>(x, y) :
statement(s)
return value1, value2,…
Return values
x , y = minmax(x,y)
Example
def add(x, y) :
a = x + y
return a
Example
def minmax(x, y) :
if x == y:
return None, None
mi = x if x < y else y
ma = x if x > y else y
return mi, ma
34. FUNCTIONS
#Variable scope
r = 1
for a in range(10):
r = 3
for i in range(5):
r = 8
print(r) ????
#Variable scope
a = 5
def var():
print(a)
var() ????
#Variable scope
a = 5
def var():
a += 5
print(a)
var() ????
35. FUNCTIONS
#Variable scope
a = 5
def var():
global a
a += 5
print(a)
var() ????
“UnboundLocalError: local variable 'a' referenced before assignment“
36. FUNCTIONS
Quiz Time
10 Min. Q3
“ What is my BMI level? : Function Version“
F1 : getInfo() #get user information and return informations
F2 : BMI(…. , ……) #calculate and return BMI level
F3 : showInfo(…,….,…,..) #display summary information
# get information, calculate BMI and display of N users
F4 : getNInfo(n)
37. FUNCTIONS
#main program
import bmi
bmi.getInfo()
bmi.BMI(weight,height)
bmi.showInfo()
#External function
#bmi.py
def getInfo():
………
def BMI(weight,height):
……..
def showInfo(….,..,.…):
………
#main program
from bmi import bmi
bmi.getInfo()
bmi.BMI(weight,height)
bmi.showInfo()
# External module function
# bmi/bmi.py
def getInfo():
………
def BMI(weight,height):
……..
def showInfo(….,..,.…):
………
40. PYTHON DATA STRUCTURES
List
[1,2,3,4,5,6,7,8,9,10]
_list = [1, ”A”, [1], 1.0] #multiple type in one list object
a = _list[0] #access one element
b = _list[0:3] #access multiple elements
_list.append(10) #add new element
_list.pop(), _list.pop(index) #remove using index
_list.remove(value) #remove using value
41. PYTHON DATA STRUCTURES
Using Lists as Stacks
stack = [3, 4, 5]
stack.append(6)
stack.append(7)
print(stack)
stack.pop()
print(stack)
stack.pop()
stack.pop()
print(stack)
42. PYTHON DATA STRUCTURES
Using Lists as Queues
from collections import deque
queue = deque(["Eric", "John", "Michael"])
queue.append("Terry")
queue.append("Graham")
queue.popleft()
queue.popleft()
print(queue)
44. PYTHON DATA STRUCTURES
Generate list
squares = [x**2 for x in range(10)]
squares = list(map(lambda x: x**2, range(10)))
map
map( lambda <> , <>, <input>) #~ short for
50. PYTHON DATA STRUCTURES
del #remove list or elements list
a = [-1, 1, 66.25, 333, 333, 1234.5]
del a[0]
del a[2:4]
del a[:]
del a #remove variable “a” from memory
51. FUNCTIONS
Quiz Time
10 Min. Q4
“ STATISTICS Time“
1. Loop for get 10 numbers from input and insert to list
2. Create function for calculate:
- Mean (Average)
- Min
- Max
- Variance #calculate from the equation only
3. Show values
http://www.mathsisfun.com/data/standard-deviation.html
52. PYTHON DATA STRUCTURES
Tuple #sequence data
(1,2,3,4,5,6,7,8,9,10)
_tuple = 4,5,6,[1],"hello" #multiple type in one Tuple object
a = _tuple[0] #access one element
b = _tuple[0:3] #access multiple elements
_tuple.count(x) #count number of x in tuple
_tuple.index(x) #find index of x in tuple
_tuple[0] = 1 #cannot edit element value in tuple
53. PYTHON DATA STRUCTURES
Concat Tuple
a = 1,2,3,4,5,6,[1],”hello"
a += tuple([100])
print(a)
(1, 2, 3, 4, 5, 6, [1], 'hello', 100)
54. PYTHON DATA STRUCTURES
List to Tuple
t = tuple([1,2,3,4,5,6])
print(t)
(1, 2, 3, 4, 5, 6)
print format using tuple
print(“%s > %s ” %(50,10) )
50 > 10
55. PYTHON DATA STRUCTURES
Sets
{'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
_set = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
#multiple type in one set object
a = _set.pop() #get first element of set
_set.remove(x) #remove element x
_set.add(x) #add new element
len(_set) #get size of set
56. PYTHON DATA STRUCTURES
_set.intersection(a) #get intersect element on set a
_set.issubset(a) #Is subset of set a?
_set.difference(a) #get difference element from set a
_set.union(a) #get union element with set a
57. PYTHON DATA STRUCTURES
Sets
a = {'apple', 'orange', 'apple', 'pear', 'orange', ‘banana'}
print(a)
{'apple', 'orange', 'banana', 'pear'}
a = set(“ABCDEFG”)
print(a)
{'E', 'B', 'A', 'F', 'G', 'C', 'D'}
58. PYTHON DATA STRUCTURES
a = set([4,5,1,2,3])
print(a)
{1, 2, 3, 4, 5} #element will be sorted automatically
a = set([4,5,1,2,3])
b = set([4,5,1])
print(a.intersection(b))
{1, 4, 5}
62. PYTHON DATA STRUCTURES
Quiz Time
5 Min. Q5
“ Similar Like Number “
IR = {11, 2, 3, 4, 15, 6, 7, 8, 9, 10}
CA = {15, 2, 3, 4, 15, 6, 17, 8, 19, 10}
SIM (IR,CA) = 0.58333
63. PYTHON DATA STRUCTURES
Quiz Time
5 Min. Q5
“ Like Number “
1. Get two set of numbers(10 numbers) from two users.
2. Create function for calculate Jaccard similarity
3. Display the similarity.
64. PYTHON DATA STRUCTURES
Dict
{'apple' : 0, 'orange' : 1, 'pear' : ‘Hello'} #key, value structure
_dict = {'apple' : 0, 'orange' : 1, 'pear' : ‘Hello'} #multiple type in
one dict object
_dict.pop() #get first element of dict
_dict.keys() #get all key of dict
_dict.values() #get all value of dict
_dict[index] = x #add new element to dict (key,value)
len(_dict) #get size of dict
65. PYTHON DATA STRUCTURES
a = {'apple' : 0, 'orange' : 1, 'pear' : ‘Hello'}
print(a[‘apple’])
0
a = {'apple' : 0, 'orange' : 1, 'pear' : ‘Hello'} for k in a:
print(a[k])
0
1
‘hello’
67. PYTHON DATA STRUCTURES
File
f = open(<filename>,’r’) #open file for read
f = open(<filename>,’w’) #open file for write new
f = open(<filename>,’a’) #open file for write append
f.readline() #read next line
f.readlines() #read all lines
f.close() #read all lines
68. PYTHON DATA STRUCTURES
file.txt
My name is python.
I am a programmer.
I have no life.
with open(“file.txt” , ’r’) as f:
first = f.readline()
for line in f:
print(line)
My name is Python.
I am a programmer.
I have no life.
69. PYTHON DATA STRUCTURES
file.txt
My name is python.
I am a programmer.
I have no life.
with open(“file.txt” , ’r’) as f:
lines = f.readlines()
print(lines)
['My name is Python.n', 'I am a programmer.n', 'I have no life.']
70. PYTHON DATA STRUCTURES
with open(“write.txt” , ’w’) as f:
f.write(“Hellon”)
write.txt
Hello
with open(“write.txt” , ’a’) as f:
f.write(“Worldn”)
write.txt
Hello
World
71. PYTHON DATA STRUCTURES
file.txt
My name is python.
I am a programmer.
I have no life.
f = open(“file.txt” , “r”)
lines = f.readlines()
print(lines)
f.close()
['My name is Python.n', 'I am a programmer.n', 'I have no life.']
72. PYTHON DATA STRUCTURES
String
str = “hello world” #create string
len(str) #get string length
str[i:j] # get string from index i to index j - 1
str[i] #get character at index i
str.replace(str1,str2) #replace str1 with str2 in string str
https://docs.python.org/2/library/string.html
str.splite(sep) #split string by string sep
75. PYTHON DATA STRUCTURES
Quiz Time
10 Min. Q6
“ Word Count “
file.txt
My name is python
I am a programmer
I have no life
I : 2
my : 1
name : 1
is : 1
……..
1. Use dictionary structure to store words and count number
each word in the document.
2. Show output , by using print command to show values in
dictionary Ex. print(dict).
78. ERROR AND EXCEPTION
import sys
try:
str = "hello"
print(str[100])
except:
tb = sys.exc_info()[1]
print(tb)
https://docs.python.org/3/library/exceptions.html
string index out of range
79. ERROR AND EXCEPTION
Input validation
while(True):
try:
n = int(input("age : "))
break
except:
print("Age is invalid, please try agian.")
https://docs.python.org/3/library/exceptions.html
80. VARIABLES AND EXPRESSIONS
Quiz Time “ Input validation “
FRIST NAME:
LAST NAME:
AGE:
GENDER:
TEL:
WEIGHT (KG.):
HEIGHT (CM.) :
5 Min. Q7
Create function for validate input value
82. OBJECT ORIENTED WITH PYTHON
class ClassName:
'Optional class documentation string'
class_suite
https://www.tutorialspoint.com/python/python_classes_objects.htm
1. The class has a documentation string, which can be accessed
via ClassName.__doc__.
2. The class_suite consists of all the component statements defining class members,
data attributes and functions
83. OBJECT ORIENTED WITH PYTHON
https://www.tutorialspoint.com/python/python_classes_objects.htm
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print("Total Employee %d") % Employee.empCount
85. OBJECT ORIENTED WITH PYTHON
https://www.tutorialspoint.com/python/python_classes_objects.htm
Class Inheritance
class SubClassName (ParentClass1[, ParentClass2, ...]):
'Optional class documentation string'
class_suite
92. MULTITHREADED PROGRAMMING
Background Executor
thread.start_new_thread ( function, args[, kwargs] )
import thread
import time
# Define a function for the thread
def print_time( threadName, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
print "%s: %s" % ( threadName, time.ctime(time.time()) )
# Create two threads as follows
try:
thread.start_new_thread( print_time, ("Thread-1", 2, ) )
thread.start_new_thread( print_time, ("Thread-2", 4, ) )
except:
print "Error: unable to start thread"
while 1:
pass
93. MULTITHREADED PROGRAMMING
Parallele Processing
p = Pool(<Number of Executor>)
p.map(<function>,data)
from multiprocessing import Pool
def f(x):
return x*x
p = Pool(5)
ans = p.map(f, [1, 2, 3])
[1, 4, 9]
- Use it if you have more than one/two cores on your computer and
more data point, overhead will occur when start new thread
95. INSTALL/CREATE AND USING PYTHON LIBRARY
“ pip install <packet name> ”
install via pip
Ex. pip install pickle
pickle.dump()
pickle.load()
96. INSTALL/CREATE AND USING PYTHON LIBRARY
“ python setup.py install ”
install via source code
https://github.com/tomerfiliba/rpyc
97. INSTALL/CREATE AND USING PYTHON LIBRARY
Using library
import <packet name>
from <packet folder name> import <packet name>
import time
t = time.time()
from date time import datetime
dt = datetime.now()
98. INSTALL/CREATE AND USING PYTHON LIBRARY
Where is library install path
import sys
sys.path
import time
t = time.time()
from date time import datetime
dt = datetime.now()
99. INSTALL/CREATE AND USING PYTHON LIBRARY
Remote Python Call
pip install rpyc or download add install via
“python setup.py install”
def printMe(text) printMe(text)
100. INSTALL/CREATE AND USING PYTHON LIBRARY
import rpyc
from rpyc.utils.server import ThreadedServer
class MyService(rpyc.Service):
def exposed_add(self, a, b):
return a + b
def exposed_sub(self, a, b):
return a - b
def exposed_mul(self, a, b):
return a * b
def exposed_div(self, a, b):
return a / b
def foo(self):
print “foo"
if __name__ == "__main__":
server =
ThreadedServer(MyService, port = 12345)
server.start()
client slide
import rpyc
import rpyc
conn = rpyc.connect("localhost", 12345)
x = conn.root.add(4,7)
print(x)
server slide