Disclaimer: The main motive to provide this solution is to help and support those who are unable to do these courses due to facing some issue and having a little bit lack of knowledge. All of the material and information contained on this website is for knowledge and education purposes only.
Try to understand these solutions and solve your Hands-On problems. (Not encourage copy and paste these solutions)
Course Path : Data Science/DATA SCIENCE BASICS/Python Packages and Data Access
1.Python Built-in Packages - Hands-on 1
Welcome to Python Built-In Packages-1
1.1)Python Built-In Package-SYS
import sys
import os
import io
def func1(a):
s=sys.stdout.write(a)
return s
if __name__ == "__main__":
1.2)Python Built-In Package-OS
import os
#Write your code here
s = os.getcwd()
os.mkdir('New Folder')
os.chdir(r'./New Folder')
q = os.getcwd()
os.chdir(s)
os.rename('New Folder','New Folder2')
os.chdir(r'./New Folder2')
p = os.getcwd()
os.chdir(s)
os.rmdir('New Folder2')
w = os.getcwd()
with open('.hidden.txt','w') as outfile:
outfile.write(s)
with open('.hidden1.txt', 'w') as outfile:
outfile.write(q)
with open('.hidden2.txt', 'w') as outfile:
outfile.write(p)
with open('.hidden3.txt', 'w') as outfile:
outfile.write(w)
1.3)Python Built-In Package-DATETIME
import os
import datetime
def func1(y,m,d,ms,se,da,mi):
input_date = datetime.date(y,m,d)
input_date1= datetime.datetime(y,m,d,ms,se,da,mi)
t= input_date1 - datetime.timedelta(days=3,minutes=2,seconds=2,microseconds=1)
day = t.day
year= t.year
month = t.month
minute= t.minute
second= t.second
return input_date,input_date1,t,day,year,month,minute,second
def func2(y,m,d,ms,se,da,mi):
input_date2 = datetime.datetime(2020,1,3,10,34,24)
f = "%a %b %d %H %M: %S %Y"
s= input_date2.strftime(f)
x= datetime.datetime(y,m,d,ms,se,da,mi)
q= x.strftime(f)
z= datetime.datetime.strptime(q,f)
return x,q,z
if __name__ == "__main__":
1.4)Python Built-In Package-SHUTIL
import os
import shutil
# Source path
source = (r'/projects/challenge/New Dir/newww.txt')
# Destination path
destination = (r'/projects/challenge')
# Copy the content of
# source to destination
dest = shutil.copy(source,destination)
# Print path of newly
# created file
print("Destination path:", dest)
with open('.hidden.txt','w') as outfile:
outfile.write(dest)
- List of Fresco Play Courses without Hands-On | Fresco Play
- HMTL5 Semantics Elements MCQs Answers | Fresco Play
- HMTL5 Semantics Elements Hands-On Solutions | Fresco Play
- Styling with CSS3 Hands-On Solutions | Fresco Play
- Blockchain Intermedio MCQs Answers | Fresco Play
- Blockchain - Potentes Nexus MCQs Answers | Fresco Play
- Azure Essentials MCQs Answers | Fresco Play
- AWS Essentials MCQs Answers | Fresco Play
2.Python Built-in Packages - Hands-on 2
Welcome to Python Built-In Packages-2
2.1)Python Built-In Package-COLLECTIONS
import os
from collections import *
# Enter your code here.
#namedtuple
def func1(x,y):
sal = namedtuple('player','name,runs')
s= sal(x,y)
return s
#deque
def func2(s):
mal = [s]
d=deque(mal)
return d
#Counter
def func3(x):
e=Counter(x)
return e
#Ordereddict
def func4(m,n,o,p,q):
d=OrderedDict()
d[1]=m
d[2]=n
d[3]=o
d[4]=p
d[5]=q
return d
#defaultdict
def func5(a,b):
s=defaultdict(list)
s[0]=a;
s[1]=b;
return s
'''For testing the code, no input is to be provided'''
if __name__ == "__main__":
2.2)Python Built-In Package-ITERTOOLS
import os
from itertools import *
# Enter your code here.
#product
def func1(w,x,y,z):
a=[w,x]
b=[y,z]
prod=product(a,b,repeat=2)
return(list(prod))
#permutation
def func2(x,y,z):
a=[x,y,z]
perm = permutations(a,3)
return(list(perm))
#combination
def func3(x,y,z):
a=[x,y,z]
comb= combinations(a,2)
return(list(comb))
#combination with replacement
def func4(x,y,z):
a=[x,y,z]
comb_wr=combinations_with_replacement(a,2)
return(list(comb_wr))
#accumulate
def func5(m,n,o,p,q):
a=[m,n,o,p,q]
accum=accumulate(a, func=min)
return(list(accum))
'''For testing the code, no input is to be provided'''
if __name__ == "__main__":
3.Regular Expression - Hands-on
Welcome to Python Regular Expressions
3.1)Python Regular Expresions – Hands-ON(1)
import os
import re
# Enter your code here
def function(a):
match = bool(re.match(r'^[AEIOU].*[aeiou]$',a))
return match
if __name__ == "__main__":
3.2)Python Regular Expresions –
Hands-ON(2)
import os
import re
def function(a):
m= bool(re.match(r"(e\w+|E\w+)\W(e\w+|E\w+)",a))
return m
if __name__ == "__main__":
3.3)Python Regular Expresions – Hands-ON(3)
import os
import re
# Enter your code here
def function(a):
result= bool(re.match(r"^[a-zA-Z]",a))
return result
if __name__ == "__main__":
3.4)Python Regular Expresions – Hands-ON(4)
import os
import re
# Enter your code here. Read input from STDIN. Print output to STDOUT
def main(x):
pattern= r"\b([A-Z][a-z]+|[A-Za-z]?)\s+\w+\s+(\d+)\b"
matches= re.finditer(pattern, x)
names = []
values= []
for matchNum, match in enumerate(matches, start=1):
names.append(match.group(1))
values.append(match.group(2))
dicts= dict(zip(names, values))
return dicts
'''For testing the code, no input is to be provided'''
if __name__ == "__main__":
3.5)Python Regular Expresions – Hands-ON(5)
'''
Online Python Compiler.
Code, Compile, Run and Debug python program online.
Write your code in this editor and press "Run" button to execute it.
'''
import os
import re
# Enter your code here
sample_text=['199.72.81.55 - - [01/Jul/1995:00:00:01 -0400] "GET /history/apollo/ HTTP/1.0" 200 6245',
'unicomp6.unicomp.net - - [01/Jul/1995:00:00:06 -0400] "GET /shuttle/countdown/ HTTP/1.0" 200 3985',
'199.120.110.21 - - [01/Jul/1995:00:00:09 -0400] "GET /shuttle/missions/sts-73/mission-sts-73.html HTTP/1.0" 200 4085',
'burger.letters.com - - [01/Jul/1995:00:00:11 -0400] "GET /shuttle/countdown/liftoff.html HTTP/1.0" 304 0',
'199.120.110.21 - - [01/Jul/1995:00:00:11 -0400] "GET /shuttle/missions/sts-73/sts-73-patch-small.gif HTTP/1.0" 200 4179',
'burger.letters.com - - [01/Jul/1995:00:00:12 -0400] "GET /images/NASA-logosmall.gif HTTP/1.0" 304 0',
'burger.letters.com - - [01/Jul/1995:00:00:12 -0400] "GET /shuttle/countdown/video/livevideo.gif HTTP/1.0" 200 0',
'205.212.115.106 - - [01/Jul/1995:00:00:12 -0400] "GET /shuttle/countdown/countdown.html HTTP/1.0" 200 3985',
'd104.aa.net - - [01/Jul/1995:00:00:13 -0400] "GET /shuttle/countdown/ HTTP/1.0" 200 3985',
'129.94.144.152 - - [01/Jul/1995:00:00:13 -0400] "GET / HTTP/1.0" 200 7074',
'unicomp6.unicomp.net - - [01/Jul/1995:00:00:14 -0400] "GET /shuttle/countdown/count.gif HTTP/1.0" 200 40310',
'unicomp6.unicomp.net - - [01/Jul/1995:00:00:14 -0400] "GET /images/NASA-logosmall.gif HTTP/1.0" 200 786',
'unicomp6.unicomp.net - - [01/Jul/1995:00:00:14 -0400] "GET /images/KSC-logosmall.gif HTTP/1.0" 200 1204',
'd104.aa.net - - [01/Jul/1995:00:00:15 -0400] "GET /shuttle/countdown/count.gif HTTP/1.0" 200 40310',
'd104.aa.net - - [01/Jul/1995:00:00:15 -0400] "GET /images/NASA-logosmall.gif HTTP/1.0" 200 786']
listToStr = ' '.join([str(elem) for elem in sample_text])
def func1():
r = r'([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}|[A-Za-z0-9]+\.[A-Za-z0-9]+\.[A-Za-z-0-9]+)'
kal = re.findall(r, listToStr)
hosts= list()
for i in kal:
hosts.append(i)
print(hosts)
def func2():
m = r'(\d\d/[A-z]{3}/\d{4}:\d\d:\d\d:\d\d\s-\d{4})'
gal = re.findall(m, listToStr)
timestamps= list()
for i in gal:
timestamps.append(i)
print(timestamps)
def func3():
q = r'GET\s/[a-zA-Z0-9]*/*[a-zA-Z-.0-9]*/*[A-Za-z0-9-]*/*[A-Za-z0-9.-]*\s*[A-Za-z]*/[0-9.]*'
zal = re.findall(q, listToStr)
gfl = list()
for i in zal:
gfl.append(i)
method_uri_protocol=[]
for j in gfl:
k = j.split()
sal = tuple(k)
method_uri_protocol.append(sal)
print(method_uri_protocol)
def func4():
h = r'(?:200|304|404)'
hal = re.findall(h, listToStr)
status= list()
for i in hal:
status.append(i)
print(status)
def func5():
p=r'(?:200|304|404)\s(\d+)'
yal = re.findall(p, listToStr)
content_size= list()
for i in yal:
content_size.append(i)
print(content_size)
'''For testing the code, no input is to be provided'''
if __name__ == "__main__":
func1()
func2()
func3()
func4()
func5()
4.Requests - Hands-on
Welcome to Python Third Party - Requests
import requests
from requests.exceptions import HTTPError
response = requests.get('https://api.github.com')
try:
a= response.status_code
b= response.encoding
c= response.text
print(a)
print(b)
print(c)
# If the response was successful, no Exception will be raised
except HTTPError as http_err:
print('HTTP error occurred: {http_err}')
except Exception as err:
print('Other error occurred: {err}')
else:
print('Success!')
a=str(a)
b=str(b)
c=str(c)
with open(".hidden.txt","w") as f:
f.write(a)
with open(".hidden1.txt","w") as f:
f.write(b)
with open(".hidden2.txt","w") as f:
f.write(c)
5.Serialization and De-serialization - Hands-on
Welcome to Python Serilalisation and De-Serialisation
5.1)Python Package Pickle- Hands-ON(1)
# Enter your code here.
import pickle
import os
data= {
"a":[5,9],
"b":[5,6],
"c":["Pickle is","helpful"]
}
#Dump file in pickle
with open("test.pkl",'wb') as f:
pickle.dump(data,f)
#Read data back from pickle
with open("test.pkl","rb") as f:
data=pickle.load(f)
print(data)
pickles = []
for root,dirs,files in os.walk("./"):
# root is the dir we are currently in, f the filename that ends on ...
pickles.extend( (os.path.join(root,f) for f in files if f.endswith(".pkl")) )
pickles=str(pickles)
print(pickles)
with open('.hidden.txt','w') as outfile:
outfile.write(pickles)
5.2)Python Package Pickle- Hands-ON(2)
# Enter your code here.
import os
import pickle
class Player:
def __init__(self, name, runs):
self.name = name
self.runs = runs
#Write code here to access value for name and runs from class PLayer
myPlayer= Player("dhoni",10000)
#Write code here to store the object in pickle file
with open("test.pickle",'wb') as f:
pickle.dump(myPlayer,f, protocol = pickle.HIGHEST_PROTOCOL)
del myPlayer
#Write code here to read the pickle file
with open("test.pickle","rb") as f:
myPlayer=pickle.load(f)
print(myPlayer.name)
print(myPlayer.runs)
5.3)Python Package Pickle- Hands-ON(3)
import os
import builtins
import pickle
import sys
sys.tracebacklimit=0
import traceback
import io
from logging import Logger
safe_builtins = {
'range',
'complex',
'set',
'frozenset'
}
class RestrictedUnpickler(pickle.Unpickler):
def find_class(self, module, name):
# Only allow safe classes from builtins.
if module == "builtins" and name in safe_builtins:
return getattr(builtins, name)
raise pickle.UnpicklingError("global '%s.%s' is forbidden" % (module, name))
# Forbid everything else.
def restricted_loads(s):
return RestrictedUnpickler(io.BytesIO(s)).load()
def func1(a):
try:
x= restricted_loads(pickle.dumps(a))
return x
except pickle.UnpicklingError :
s=traceback.format_exc()
return s
def func2(s):
try:
x= restricted_loads(pickle.dumps(slice(0,8,3)))
return s[x]
except pickle.UnpicklingError :
s=traceback.format_exc()
return s
if __name__ == "__main__":
a=range(int(input()))
b=func1(a)
print(b)
print("Traceback (most recent call last):")
y=tuple(input())
z=func2(y)
print(z)
5.4)Python Package Pickle- Hands-ON(4)
import os
import json
def func1(value):
a= json.loads(value)
datas=a["data"]
return datas
if __name__ == "__main__":
5.5)Python Package Pickle- Hands-ON(5)
import os
import json
def func1(value):
a= json.dumps(value)
b= json.loads(value)
return b
if __name__ == "__main__":
6.SQLAlchemy - Hands-on
Welcome to Python Database Connectivity - SQLAlchemy
6.1)Database Connectivity - CRUD operations using SQLAlchemy(RAW SQL)
from sqlalchemy import create_engine
db_string = "sqlite:///tests.db"
db = create_engine(db_string)
#create
db.execute("CREATE TABLE IF NOT EXISTS players (plyid text, plyname text, runs text)")
db.execute("INSERT INTO players (plyid, plyname, runs) VALUES ('10001','ply1','100'),('10002','ply2','80'),('10003','ply3','65'),('10004','ply4','95'),('10005','ply5','99')")
# Read
result_set = db.execute("SELECT * FROM players")
s=[]
for r in result_set:
s.append(r)
#Update
mal = db.execute("UPDATE players SET runs='100' WHERE plyname='ply5'")
result_set1 = db.execute("SELECT * FROM players")
q=[]
for w in result_set1:
q.append(w)
#Delete
db.execute("DELETE FROM players WHERE plyname='ply5'")
result_set2 = db.execute("SELECT * FROM players")
e=[]
for h in result_set2:
e.append(h)
print(s)
print(q)
print(e)
s=str(s)
q=str(q)
e=str(e)
with open(".hidden.txt",'w') as f:
f.write(s)
with open(".hidden1.txt",'w') as f:
f.write(q)
with open(".hidden2.txt",'w') as outfile:
outfile.write(e)
6.2)Database Connectivity - CRUD operations using SQLAlchemy(SQL ORM)
from sqlalchemy import create_engine
from sqlalchemy import Column, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
db_string = "sqlite:///tests.db"
db = create_engine(db_string)
base = declarative_base()
class Teacher(base):
__tablename__ = 'students'
stdid = Column(String, primary_key = True)
stdname = Column(String)
subjects = Column(String)
marks = Column(String)
#Define table name and column name
Session = sessionmaker(db)
session = Session()
base.metadata.create_all(db)
#Create
stgd1 = Teacher(stdid="10001", stdname="std1",subjects="Maths", marks="100")
stgd2 = Teacher(stdid="10002", stdname="std2",subjects="Physics", marks="80")
stgd3 = Teacher(stdid="10003", stdname="std3",subjects="English", marks="65")
stgd4 = Teacher(stdid="10004", stdname="std4",subjects="Social", marks="95")
stgd5 = Teacher(stdid="10005", stdname="std5",subjects="Chemistry", marks="99")
session.add_all([stgd1,stgd2,stgd3,stgd4,stgd5])
session.commit()
#Read
students = session.query(Teacher)
s = []
for u in students:
k = [u.stdid,u.stdname,u.subjects,u.marks]
s.append(k)
print(s)
#Update
stgd5.subjects="Language"
session.commit()
students = session.query(Teacher)
for n in students:
h = n.stdid,n.stdname,n.subjects,n.marks
q = list(h)
print(q)
#Delete
session.delete(stgd5)
students = session.query(Teacher)
e = []
for c in students:
r = [c.stdid,c.stdname,c.subjects,c.marks]
e.append(r)
print(e)
s=str(s)
q=str(q)
e=str(e)
with open(".hidden.txt",'w') as f:
f.write(s)
with open(".hidden1.txt",'w') as f:
f.write(q)
with open(".hidden2.txt",'w') as outfile:
outfile.write(e)
- List of Fresco Play Courses without Hands-On | Fresco Play
- HMTL5 Semantics Elements MCQs Answers | Fresco Play
- HMTL5 Semantics Elements Hands-On Solutions | Fresco Play
- Styling with CSS3 Hands-On Solutions | Fresco Play
- Blockchain Intermedio MCQs Answers | Fresco Play
- Blockchain - Potentes Nexus MCQs Answers | Fresco Play
- Azure Essentials MCQs Answers | Fresco Play
- AWS Essentials MCQs Answers | Fresco Play