#python 5
#Doc String
def squarDoc Stringe(n):
'''Takes in a number n, returns the square of n'''
return n**2
print(square.__doc__)
Takes in a number n, returns the square of n
#return function
def addEven(n, m):
if n%2 == 0 and m%2 == 0:
return n+m
else:
return n*m
print(addEven(2,2))
print(addEven(2,3))
4
6
#In-Built Function
#abs
complex_num = (3+10j)
print("The magnitude of the complex number is:", abs(complex_num))
The magnitude of the complex number is: 10.44030650891055
#divmod
divmod(10,7)
(1, 3)
divmod(13.5,7.8)
(1.0, 5.7)
#Enumerate
x = ('apple', 'banana', 'cherry')
y = enumerate(x)
print(list(y))
[(0, 'apple'), (1, 'banana'), (2, 'cherry')]
#Filter
ages = [5, 12, 17, 18, 24, 32]
def myFunc(x):
if x < 18:
return False
else:
return True
adults = filter(myFunc, ages)
for x in adults:
print(x)
18
24
32
#Map
def myfunc(a, b):
return a + b
x = map(myfunc, ('apple', 'banana', 'cherry'), ('orange', 'lemon',
'pineapple'))
print(x)
print(list(x))
<map object at 0x000001996AFA2F70>
['appleorange', 'bananalemon', 'cherrypineapple']
import functools
lis = [1, 3, 5, 6, 2, ]
print("The sum of the list elements is : ", end="")
print(functools.reduce(lambda a, b: a+b, lis))
print("The maximum element of the list is : ", end="")
print(functools.reduce(lambda a, b: a if a > b else b, lis))
The sum of the list elements is : 17
The maximum element of the list is : 6
#isinstance
class myObj:
name = "John"
y = myObj()
x = isinstance(y, myObj)
print(x)
True
#lambda function
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(filter(lambda x: (x%2 == 0) , my_list))
print(new_list)
[4, 6, 8, 12]
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
while True:
choice = input("Enter choice(1/2/3/4): ")
if choice in ('1', '2', '3', '4'):
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))
elif choice == '2':
print(num1, "-", num2, "=", subtract(num1, num2))
elif choice == '3':
print(num1, "*", num2, "=", multiply(num1, num2))
elif choice == '4':
print(num1, "/", num2, "=", divide(num1, num2))
next_calculation = input("Let's do next calculation? (yes/no):
")
if next_calculation == "no":
break
else:
print("Invalid Input")
Select operation.
1.Add
2.Subtract
3.Multiply
4.Divide
----------------------------------------------------------------------
-----
KeyboardInterrupt Traceback (most recent call
last)
<ipython-input-30-efd003dd92fd> in <module>
14
15 while True:
---> 16 choice = input("Enter choice(1/2/3/4): ")
17
18 if choice in ('1', '2', '3', '4'):
~\anaconda3\lib\site-packages\ipykernel\kernelbase.py in
raw_input(self, prompt)
858 "raw_input was called, but this frontend does
not support input requests."
859 )
--> 860 return self._input_request(str(prompt),
861 self._parent_ident,
862 self._parent_header,
~\anaconda3\lib\site-packages\ipykernel\kernelbase.py in
_input_request(self, prompt, ident, parent, password)
902 except KeyboardInterrupt:
903 # re-raise KeyboardInterrupt, to truncate
traceback
--> 904 raise KeyboardInterrupt("Interrupted by user")
from None
905 except Exception as e:
906 self.log.warning("Invalid Message:",
exc_info=True)
KeyboardInterrupt: Interrupted by user
#python 6
#Write a Python Program to implement following concepts related to
NumPy Arrays
#Creating array
import numpy as np
array1 = np.arange(0,10)
array1
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
array1[2]
#indexing
array1 = np.arange(12).reshape(4,3)
array1
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])
array1[3][1]
10
#Slicing
array1 = np.arange(9)
array1
array([0, 1, 2, 3, 4, 5, 6, 7, 8])
array1[3:6]
array([3, 4, 5])
array1[4:]
array([4, 5, 6, 7, 8])
array1[:7]
array([0, 1, 2, 3, 4, 5, 6])
array1[:]
array([0, 1, 2, 3, 4, 5, 6, 7, 8])
#np.may_share_memory
import numpy as demo
arr1 = demo.zeros([3, 4])
arr2 = arr1[::1]
mydemo = demo.may_share_memory(arr1, arr2)
print (mydemo)
True
#Fancy Indexing
import numpy as np
rand = np.random.RandomState(42)
x = rand.randint(100, size=10)
print(x)
[51 92 14 71 60 20 82 86 74 74]
[x[3], x[7], x[2]]
[71, 86, 14]
ind = [3, 7, 4]
x[ind]
array([71, 86, 60])
ind = np.array([[3, 7],
[4, 5]])
x[ind]
array([[71, 86],
[60, 20]])
X = np.arange(12).reshape((3, 4))
X
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
#Write a Python Program to implement matplotlib.pyplot
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = [1,2,3,4,5]
y = [50,40,70,80,20]
y2 = [80,20,20,50,60]
y3 = [70,20,60,40,60]
y4 = [80,20,20,50,60]
plt.plot(x,y,'g',label='Enfield', linewidth=5)
plt.plot(x,y2,'c',label='Honda',linewidth=5)
plt.plot(x,y3,'k',label='Yahama',linewidth=5)
plt.plot(x,y4,'y',label='KTM',linewidth=5)
plt.title('bike details in line plot')
plt.ylabel('Distance in kms')
plt.xlabel('Days')
plt.legend()
<matplotlib.legend.Legend at 0x1996d2b35e0>
#Write a Python Program to implement following concepts related to
Pandas
# import pandas to use pandas DataFrame
import pandas as pd
data = [('Peter', 18, 7),
('Riff', 15, 6),
('John', 17, 8),
('Michel', 18, 7),
('Sheli', 17, 5) ]
df = pd.DataFrame(data, columns =['Name', 'Age', 'Score'])
print(df)
Name Age Score
0 Peter 18 7
1 Riff 15 6
2 John 17 8
3 Michel 18 7
4 Sheli 17 5
# Read and write CSV
df = pd.read_csv('Downloads/tmdb_5000_credits.csv')
df
movie_id title \
0 19995 Avatar
1 285 Pirates of the Caribbean: At World's End
2 206647 Spectre
3 49026 The Dark Knight Rises
4 49529 John Carter
... ... ...
4798 9367 El Mariachi
4799 72766 Newlyweds
4800 231617 Signed, Sealed, Delivered
4801 126186 Shanghai Calling
4802 25975 My Date with Drew
cast \
0 [{"cast_id": 242, "character": "Jake Sully", "...
1 [{"cast_id": 4, "character": "Captain Jack Spa...
2 [{"cast_id": 1, "character": "James Bond", "cr...
3 [{"cast_id": 2, "character": "Bruce Wayne / Ba...
4 [{"cast_id": 5, "character": "John Carter", "c...
... ...
4798 [{"cast_id": 1, "character": "El Mariachi", "c...
4799 [{"cast_id": 1, "character": "Buzzy", "credit_...
4800 [{"cast_id": 8, "character": "Oliver O\u2019To...
4801 [{"cast_id": 3, "character": "Sam", "credit_id...
4802 [{"cast_id": 3, "character": "Herself", "credi...
crew
0 [{"credit_id": "52fe48009251416c750aca23", "de...
1 [{"credit_id": "52fe4232c3a36847f800b579", "de...
2 [{"credit_id": "54805967c3a36829b5002c41", "de...
3 [{"credit_id": "52fe4781c3a36847f81398c3", "de...
4 [{"credit_id": "52fe479ac3a36847f813eaa3", "de...
... ...
4798 [{"credit_id": "52fe44eec3a36847f80b280b", "de...
4799 [{"credit_id": "52fe487dc3a368484e0fb013", "de...
4800 [{"credit_id": "52fe4df3c3a36847f8275ecf", "de...
4801 [{"credit_id": "52fe4ad9c3a368484e16a36b", "de...
4802 [{"credit_id": "58ce021b9251415a390165d9", "de...
[4803 rows x 4 columns]
#groupby
gk = df.groupby('title')
gk.first()
movie_id \
title
#Horror 301325
(500) Days of Summer 19913
10 Cloverfield Lane 333371
10 Days in a Madhouse 345003
10 Things I Hate About You 4951
... ...
[REC]² 10664
eXistenZ 1946
xXx 7451
xXx: State of the Union 11679
Æon Flux 8202
cast \
title
#Horror [{"cast_id": 0, "character": "Alex's 12-
Step F...
(500) Days of Summer [{"cast_id": 4, "character": "Tom Hansen",
"cr...
10 Cloverfield Lane [{"cast_id": 2, "character": "Michelle",
"cred...
10 Days in a Madhouse [{"cast_id": 2, "character": "Nellie Bly",
"cr...
10 Things I Hate About You [{"cast_id": 2, "character": "Patrick
Verona",...
...
...
[REC]² [{"cast_id": 3, "character": "\u00c1ngela
Vida...
eXistenZ [{"cast_id": 3, "character": "Allegra
Geller",...
xXx [{"cast_id": 8, "character": "Xander
Cage", "c...
xXx: State of the Union [{"cast_id": 13, "character": "Darius
Stone / ...
Æon Flux [{"cast_id": 1, "character": "Aeon Flux",
"cre...
crew
title
#Horror [{"credit_id": "545bbac70e0a261fb6002329",
"de...
(500) Days of Summer [{"credit_id": "52fe47f99251416c750abaa5",
"de...
10 Cloverfield Lane [{"credit_id": "57627624c3a3680682000872",
"de...
10 Days in a Madhouse [{"credit_id": "594efa1fc3a36832650455ff",
"de...
10 Things I Hate About You [{"credit_id": "52fe43e6c3a36847f807731d",
"de...
...
...
[REC]² [{"credit_id": "52fe439e9251416c7501783d",
"de...
eXistenZ [{"credit_id": "52fe4325c3a36847f803db2d",
"de...
xXx [{"credit_id": "538d8c59c3a368714b004879",
"de...
xXx: State of the Union [{"credit_id": "5578b667c3a3682a7500041a",
"de...
Æon Flux [{"credit_id": "52fe4495c3a36847f809e6f3",
"de...
[4800 rows x 3 columns]
df1 = pd.DataFrame(
{
"A": ["A0", "A1", "A2", "A3"],
"B": ["B0", "B1", "B2", "B3"],
"C": ["C0", "C1", "C2", "C3"],
"D": ["D0", "D1", "D2", "D3"],
},
index=[0, 1, 2, 3],
)
df2 = pd.DataFrame(
{
"A": ["A4", "A5", "A6", "A7"],
"B": ["B4", "B5", "B6", "B7"],
"C": ["C4", "C5", "C6", "C7"],
"D": ["D4", "D5", "D6", "D7"],
},
index=[4, 5, 6, 7],
)
df3 = pd.DataFrame(
{
"A": ["A8", "A9", "A10", "A11"],
"B": ["B8", "B9", "B10", "B11"],
"C": ["C8", "C9", "C10", "C11"],
"D": ["D8", "D9", "D10", "D11"],
},
index=[8, 9, 10, 11],
)
frames = [df1, df2, df3]
result = pd.concat(frames)
#Concatenate data frames
import pandas as pd
df = pd.DataFrame({'Courses': ["Spark", "PySpark", "Python",
"Pandas"],
'Fee' : ['20000', '25000', '22000', '24000']})
df1 = pd.DataFrame({'Courses': ["Unix", "Hadoop", "Hyperion", "Java"],
'Fee': ['25000', '25200', '24500', '24900']})
df2 = pd.DataFrame({'Duration':
['30day','40days','35days','60days','55days'],
'Discount':[1000,2300,2500,2000,3000]})
df3 = pd.concat([df, df1, df2])
print(df3)
Courses Fee Duration Discount
0 Spark 20000 NaN NaN
1 PySpark 25000 NaN NaN
2 Python 22000 NaN NaN
3 Pandas 24000 NaN NaN
0 Unix 25000 NaN NaN
1 Hadoop 25200 NaN NaN
2 Hyperion 24500 NaN NaN
3 Java 24900 NaN NaN
0 NaN NaN 30day 1000.0
1 NaN NaN 40days 2300.0
2 NaN NaN 35days 2500.0
3 NaN NaN 60days 2000.0
4 NaN NaN 55days 3000.0
#Merge data frame
import pandas as pd
left = pd.DataFrame({
'id':[1,2,3,4,5],
'Name': ['Alex', 'Amy', 'Allen', 'Alice', 'Ayoung'],
'subject_id':['sub1','sub2','sub4','sub6','sub5']})
right = pd.DataFrame({
'id':[1,2,3,4,5],
'Name': ['Billy', 'Brian', 'Bran', 'Bryce', 'Betty'],
'subject_id':['sub2','sub4','sub3','sub6','sub5']})
print(pd.merge(left,right,on=['id','subject_id']))
id Name_x subject_id Name_y
0 4 Alice sub6 Bryce
1 5 Ayoung sub5 Betty
#Numeric indexing (.loc and .iloc)
import pandas as pd
import numpy as np
data = pd.DataFrame({
'age' : [ 10, 22, 13, 21, 12, 11, 17],
'section' : [ 'A', 'B', 'C', 'B', 'B', 'A', 'A'],
'city' : [ 'Gurgaon', 'Delhi', 'Mumbai', 'Delhi', 'Mumbai',
'Delhi', 'Mumbai'],
'gender' : [ 'M', 'F', 'F', 'M', 'M', 'M', 'F'],
'favourite_color' : [ 'red', np.NAN, 'yellow', np.NAN, 'black',
'green', 'red']
})
data
age section city gender favourite_color
0 10 A Gurgaon M red
1 22 B Delhi F NaN
2 13 C Mumbai F yellow
3 21 B Delhi M NaN
4 12 B Mumbai M black
5 11 A Delhi M green
6 17 A Mumbai F red
data.loc[data.age >= 15]
age section city gender favourite_color
1 22 B Delhi F NaN
3 21 B Delhi M NaN
6 17 A Mumbai F red
data.iloc[[0,2]]
age section city gender favourite_color
0 10 A Gurgaon M red
2 13 C Mumbai F yellow
#python 7
#Class & Object with self and __init__ method
class Person:
def __init__(self, name):
self.name = name
def say_hi(self):
print('Hello, my name is', self.name)
p1 = Person('Nikhil')
p2 = Person('Abhinav')
p3 = Person('Anshul')
p1.say_hi()
p2.say_hi()
p3.say_hi()
Hello, my name is Nikhil
Hello, my name is Abhinav
Hello, my name is Anshul
class Rectangle:
def __init__(self, length, breadth, unit_cost=0):
self.length = length
self.breadth = breadth
self.unit_cost = unit_cost
def get_area(self):
return self.length * self.breadth
def calculate_cost(self):
area = self.get_area()
return area * self.unit_cost
# breadth = 120 units, length = 160 units, 1 sq unit cost = Rs 2000
r = Rectangle(160, 120, 2000)
print("Area of Rectangle: %s sq units" % (r.get_area()))
Area of Rectangle: 19200 sq units
#Inheritance
class Animal:
def speak(self):
print("Animal Speaking")
class Dog(Animal):
def bark(self):
print("dog barking")
class DogChild(Dog):
def eat(self):
print("Eating bread...")
d = DogChild()
d.bark()
d.speak()
d.eat()
dog barking
Animal Speaking
Eating bread...
#Operator-Overloading
class example:
def __init__(self, X):
self.X = X
# adding two objects
def __add__(self, U):
return self.X + U.X
object_1 = example( int( input( print ("Please enter the value: "))))
object_2 = example( int( input( print ("Please enter the value: "))))
print (": ", object_1 + object_2)
object_3 = example(str( input( print ("Please enter the value: "))))
object_4 = example(str( input( print ("Please enter the value: "))))
print (": ", object_3 + object_4)
Please enter the value:
None7
Please enter the value:
None8
: 15
Please enter the value:
None6
Please enter the value:
None4
: 64
#Polymorphism
class Tomato():
def type(self):
print("Vegetable")
def color(self):
print("Red")
class Apple():
def type(self):
print("Fruit")
def color(self):
print("Red")
def func(obj):
obj.type()
obj.color()
obj_tomato = Tomato()
obj_apple = Apple()
func(obj_tomato)
func(obj_apple)
Vegetable
Red
Fruit
Red
#Error and Exceptions
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d" %c)
print("Hi I am other part of the program")
Enter a:4
Enter b:0
----------------------------------------------------------------------
-----
ZeroDivisionError Traceback (most recent call
last)
<ipython-input-109-be5b57e399df> in <module>
2 a = int(input("Enter a:"))
3 b = int(input("Enter b:"))
----> 4 c = a/b
5 print("a/b = %d" %c)
6
ZeroDivisionError: division by zero
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d"%c)
# Using Exception with except statement. If we print(Exception) it
will return exception class
except Exception:
print("can't divide by zero")
print(Exception)
else:
print("Hi I am else block")
Enter a:4
Enter b:0
can't divide by zero
<class 'Exception'>
file = open('Downloads/demo.txt','w')
file.write('Hello World')
file.write('This is our new text file')
file.write('and this is another line.')
file.write('Why? Because we can do it this easily.')
file.close()
file = open('Downloads/demo.txt', 'r')
print(file.read())
Hello WorldThis is our new text fileand this is another line.Why?
Because we can do it this easily.
file = open('Downloads/demo.txt', 'r')
print(file.read(5))
Hello
os.remove('Downloads/demo - Copy.txt')