200 Python Practice Exercises 1687850509
200 Python Practice Exercises 1687850509
In [103]:
print(x,y)
x=x+y
y=x-y
x=x-y
print(x,y)
Exercise 2: Write a Program to extract each digit from an integer in the reverse order.
For example, If the given int is 7536, the output shall be “6 3 5 7“, with a space separating the digits.
In [102]:
y=str(n)[::-1]
print(y)
type(y)
Out[102]:
str
excercise 3: Write a program that will give you the sum of 3 digits
In [35]:
print(a+b+c)
excercise 4: Write a program that will reverse a four digit number.Also it checks whether the reverse is true.
In [37]:
rev=a*1000+b*100+c*10+d
print(rev)
if x==rev:
print(True)
else:
print(False)
excercise 5: Write a program to find the euclidean distance between two coordinates.
In [40]:
import math
In [41]:
x1=float(input("x1: "))
y1=float(input("y1: "))
x2=float(input("x2: "))
y2=float(input("y2: "))
x=[x1,y1]
y=[x2,y2]
print("="*100)
x1: 4
y1: 5
x2: 6
y2: 8
==========================================================================
==========================
Eucledian distance for given co-ordinate will be 3.61
excercise 5: Write a program that will tell whether the given number is divisible by 3 & 6.
In [49]:
Excercise 6: Write a program that will take three digits from the user and add the square of each digit.
In [53]:
#123
a=n%10 #3
num=n//10 #12
b=num%10 #2
c=num//10 #1
output_value=(a**2)+(b**2)+(c**2)
print(output_value)
Excercise 7: Write a program that will check whether the number is armstrong number or not.
An Armstrong number is one whose sum of digits raised to the power three equals the
number itself. 371, for example, is an Armstrong number because 3**3 + 7**3 + 1**3 =
371.
In [54]:
a=n%10 #3
num=n//10 #12
b=num%10 #2
c=num//10 #1
Excercise 8:Write a program that will take user input of (4 digits number) and check whether the number is
narcissist number or not.
In [55]:
#1234
a=n%10 #4
num=n//10 #123
b=num%10 #3
num_1=num//10 #12
c=num_1%10 #2
d=num_1//10 #1
In [125]:
Exercise 10: Display three string “Name”, “Is”, “James” as “Name ** Is ** James”
In [126]:
print("name","is","james",sep="**")
name**is**james
Exercise 11: Convert Decimal number to octal using print() output formatting
In [129]:
number=12
print(oct(number)[-2:])
14
Exercise 12: Display float number with 2 decimal places using print()
In [137]:
num=56.87547
y=float(round(num,2))
print(y)
56.88
In [81]:
for i in range(1,n+1):
if n%i==0:
print(i,end=" ")
Exercise 14: Accept a list of 5 float numbers as an input from the user
In [144]:
l1=[]
while len(l1)<5:
n=float(input("enter the number: "))
l1.append(n)
print(l1)
Exercise 15: Write all content of a given file into a new file by skipping line number 5
In [189]:
Exercise 16: Accept any three string from one input() call
In [196]:
sep=inp.split()
#print(sep)
name1=sep[0]
name2=sep[1]
name3=sep[2]
print(name1)
print(name2)
print(name3)
enter the three names with keeping space in between: govind damodar madhav
eti
govind
damodar
madhaveti
Exercise 17: Format variables using a string.format() method. Write a program to use string.format() method
to format the following three variables as per the expected output
In [204]:
totalmoney=1200
quantity=4
price=450
Exercise 18: Check file is empty or not Write a program to check if the given file is empty or not
In [205]:
import os
size=os.stat("test file.txt").st_size
if size==0:
print("file is empty")
else:
print("file is not empty")
In [206]:
excercise 20: Write a program to find the simple interest when the value of principle,rate of interest and time
period is given.
In [45]:
Simple_interest= (P*R*T)/100
print(Simple_interest)
total_due=P+Simple_interest
Excercise 21: Write a program to find the volume of the cylinder. Also find the cost when ,when the cost of
1litre milk is 40Rs.
In [47]:
vol=3.142*(rad**2)*ht
litr=vol/1000
cost=litr*40
In [24]:
prev_num=0
for i in range(1,11):
x=i+prev_num
prev_num=i
print(x,end=" ")
1 3 5 7 9 11 13 15 17 19
Excercise 23: Write a python program to search a given number from a list
In [89]:
l1=[4,5,6,2,3,9,1,4,5,6,3]
for i in l1:
if i==n:
print("Number exist")
break
else:
print("number dont exist")
Exercise 24: Check Palindrome Number Write a program to check if the given number is a palindrome
number.
A palindrome number is a number that is same after reverse. For example 545, is the palindrome numbers
In [99]:
rev_number=str(n)[::-1]
print(rev_number)
if n==int(rev_number):
print("the given number is palindrom")
else:
print("the given number is not palindrom")
Exercise 25: Create a new list from a two list using the following condition Given a two list of numbers, write
a program to create a new list such that the new list should contain odd numbers from the first list and even
numbers from the second list.
In [100]:
l1=[1,2,3,4,5]
l2=[6,7,8,9,10]
l3=[]
for i in l1:
if i%2!=0:
l3.append(i)
for i in l2:
if i%2==0:
l3.append(i)
print(l3)
[1, 3, 5, 6, 8, 10]
Exercise 26: Calculate income tax for the given income by adhering to the below rules first 10k--> 0% second
10 --> 10% remaining-->20%
Expected Output:
For example, suppose the taxable income is 45000 the income tax payable is
In [96]:
if n<=10000:
print(n)
else:
a=n-10000
b=a-10000
c=b*0.2
d=c+1000
print(d)
In [101]:
for i in range(1,11):
for j in range(1,11):
print(i*j,end=" ")
print("\n")
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
Excercise 28: Print all the armstrong numbers in the range of 100 to 1000
In [69]:
armstrong_list=[]
for i in range(100,1000):
a=i%10 # 123-->3
num=i//10 #123-->12
b=num%10 #--->2
c=num//10 #-->1
if (a**3)+(b**3)+(c**3)==i:
armstrong_list.append(i)
print(armstrong_list)
Excercise 29: The current population of a town is 10000. The population of the town is increasing at the rate
of 10% per year. You have to write a program to find out the population at the end of each of the last 10
years. For eg current population is 10000 so the output should be like this:
In [71]:
p=10000
for i in range(1,10):
p=p-0.1*p
print(round(p),end=" ")
Excercise 30: Write a program to print all the unique combinations of two digits from 1 to 4 for ex (1,2),
(2,3).....
In [72]:
for i in range(1,5):
for j in range(1,5):
if i != j:
print(i,j)
1 2
1 3
1 4
2 1
2 3
2 4
3 1
3 2
3 4
4 1
4 2
4 3
excercise 31:Write a program to print whether a given number is prime number or not
In [68]:
new=[]
if x==1:
print("1 is not prime number")
else:
for i in range(1,x+1):
if x%i==0:
new.append(i)
#print(new)
if len(new) > 2:
print("it is not a prime number")
else:
print("it is prime number ")
In [ ]:
excercise 32: User will provide 2 numbers you have to find the HCF of those 2 numbers
In [73]:
x_div=[]
y_div=[]
for i in range(1,x+1):
if x%i==0:
x_div.append(i)
for i in range(1,y+1):
if y%i==0:
y_div.append(i)
comman_list=[]
for i in x_div:
if i in y_div:
comman_list.append(i)
Excercise 33: User will provide 2 numbers you have to find the by LCM of those 2 numbers
In [74]:
if a>b:
greater=a
else:
greater=b
while(True):
if (greater%a==0) and (greater%b==0):
LCM=greater
break
greater+=1
print(LCM)
excercise 34: Write a program that take a user input of three angles and will find out whether it can form a
triangle or not.
In [42]:
excercise 35:Write a program that will determine weather when the value of temperature and humidity is
provided by the user.
In [51]:
excercise 36:Write a program that will take user input of cost price and selling price and determines whether
its a loss or a profit
In [43]:
if (sell-cost)>0:
amount=sell-cost
print("it is profit by ",amount)
else:
amount=sell-cost
print("it is loss by ",amount)
excercise 37-Write a program that will give you the in hand salary after deduction of HRA(10%),
DA(5%),
PF(3%),
and tax
(11-20lakh–20%),
(20< _ – 30%)
In [56]:
if salary in range(500000,1000000):
salary=salary-salary*0.1
elif salary in range(1100000,2000000):
salary=salary-salary*0.2
elif salary> 2000000:
salary=salary-salary*0.3
else:
print("no tax")
HRA=salary*0.10 # 63000
DA=salary*0.05 #31500
PF=salary*0.03 #18900
remain=salary-(HRA+DA+PF)
if remain in range(1000,99999):
print("in hand salary after tax/HRA/DA/PF cutting",remain/1000,"k")
elif remain in range(100000,9999999):
print("in hand salary after tax/HRA/DA/PF cutting",remain/100000,"lakh")
else:
print("in hand salary after tax/HRA/DA/PF cutting",remain/10000000,"Cr")
2.kl to miles
3.usd to inr
4.exit
In [57]:
if user_input==1:
var1=int(input("enter the value in cm"))
output=var1/30.48
print(output,'ft')
elif user_input==2:
var2=int(input("enter the value in km"))
output=var2/1.609
print(output,'miles')
elif user_input==3:
var3=int(input("enter the value in usd"))
output=var3*81.80
print(output,"Inr")
else:
print("Exit")
Excercise 39:Write a program that will tell the number of dogs and chicken are there when the user will
provide the value of total heads and legs.
In [59]:
# number of head--> 1 1
# number of legs--> 4 2
if head/legs==0.25:
number_of_dogs=legs/4
print("there are ",round(number_of_dogs),'number of dogs')
elif head/legs==0.5:
number_of_chicken=legs/2
print("there are ",round(number_of_chicken),'number of chicken')
else:
print("enter correct numbers")
excercise 40: Write a program to find the sum of first n numbers, where n will be provided by the user. Eg if
the user provides n=10 the output should be 55.
In [61]:
x=0
for i in range(1,user_input+1):
x=x+i
i+=1
print(x)
Excercise 41: Write a program that can multiply 2 numbers provided by the user without using the * operator
In [62]:
result=0
for i in range(0,y):
result=result+x
print(result)
Excercise 42:Write a program that can find the factorial of a given number provided by the user.
In [64]:
factorial=1
if n < 0 :
print("factorial dont exist for negative number")
elif n==0:
print("for zero factorial is always one")
else:
for i in range(1,n+1):
factorial=factorial*i
print(factorial)
In [34]:
for i in range(0,n+1):
for j in range(0,i):
print(i,end=" ")
print("\n")
2 2
3 3 3
4 4 4 4
5 5 5 5 5
In [207]:
while i <10:
for i in range(1,11):
print(i,end=" ")
1 2 3 4 5 6 7 8 9 10
In [28]:
num=1
for i in range(0,n):
for j in range(0,i+1):
print(num,end=" ")
num=num+1
print()
Excercise 46
In [227]:
#1,2,3,4,5
for i in range(1,n+1):
for j in range(1,i+1):
print(j,end=" ")
print("\n")
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Excercise 47
In [27]:
list1=[]
for i in range(0,n):
temp=[]
for j in range(0,i+1):
if j==0 or j==i:
temp.append(1)
else:
temp.append(list1[i-1][j]+list1[i-1][j-1])
list1.append(temp)
#print(list1)
for i in range(n):
for j in range(0,n-i-1):
print(" ",end="")
for j in range(0,i+1):
print(list1[i][j],end=" ")
print()
Exercise 48: Calculate the sum of all numbers from 1 to a given number
Write a program to accept a number from a user and calculate the sum of all numbers from 1 to a given
number
In [229]:
x=0
for i in range(1,n+1):
x=x+i
print(x)
Exercise 49: Write a program to print multiplication table of a given number For example, num = 2 so the
output should be
In [233]:
for i in range(1,11):
x=n*i
print(x,end=" ")
Exercise 50: Display numbers from a list using loop Write a program to display only those numbers from a list
that satisfy the following conditions
If the number is greater than 150, then skip it and move to the next number
In [236]:
num=[12,75,150,180,145,525,50]
for i in num:
if i>500:
break
elif i>150:
continue
else:
if i%5==0:
print(i)
75
150
145
Exercise 51: Count the total number of digits in a number Write a program to count the total number of digits
in a number using a while loop.
In [246]:
x=list(n)
count=0
while count<len(x):
for i in x:
count+=1
print(count)
Exercise 52: Print the following pattern Write a program to use for loop to print the following reverse number
pattern
In [263]:
for i in range(n,0,-1):
for j in range(i,0,-1):
print(j,end=" ")
print("\n")
4 3 2 1
3 2 1
2 1
In [265]:
l1=[1,2,3,4,5]
for i in l1[::-1]:
print(i,end=" ")
5 4 3 2 1
In [273]:
for i in range(-10,0):
print(i,end=" ")
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Exercise 55: Use else block to display a message “Done” after successful execution of for loop
For example, the following loop will execute without any error.
In [277]:
for i in range(0,5):
print(i)
else:
print("done !!")
0
1
2
3
4
done !!
Exercise 56: Write a program to display all prime numbers within a range
Note: A Prime Number is a number which only divisible by one and number itself.but 1 is not prime number
In [322]:
def prime(n):
if n<=1:
return False
else:
l1=[]
for i in range(1,n+1):
if n%i==0:
l1.append(i)
#print(l1)
if len(l1)<=2:
return True
else:
return False
for i in range(inp1,inp2+1):
if prime(i)==True:
print(i,end=" ")
Exercise 57: Display Fibonacci series up to 10 terms The Fibonacci Sequence is a series of numbers. The
next number is found by adding up the two numbers before it. The first two numbers are 0 and 1.
For example, 0, 1, 1, 2, 3, 5, 8, 13, 21. The next number in this series above is 13+21 = 34.
In [20]:
num1=0
num2=1
print(num1,end=" ")
print(num2,end=" ")
for i in range(0,n):
num3=num1+num2
num1=num2
num2=num3
print(num3,end=" ")
Exercise 58: Find the factorial of a given number Write a program to use the loop to find the factorial of a
given number.
The factorial (symbol: !) means to multiply all whole numbers from the chosen number down to 1.
In [28]:
fact=1
for i in range(1,n+1):
fact=fact*i
print(fact)
76542
Expected output:
24567
In [36]:
x=str(n)
x=list(x)[::-1]
z=int("".join(x))
print(z)
#print(type(z))
Exercise 60: Use a loop to display elements from a given list present at odd index positions
my_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
In [42]:
my_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
Out[42]:
Exercise 61: Calculate the cube of all numbers from 1 to a given number Write a program to rint the cube of
all numbers from 1 to a given number
Given:
input_number = 6
In [44]:
n=6
for i in range(1,7):
x=pow(i,3)
#print(x)
print("current number is {} and the cube is {}".format(i,x))
Exercise 62: Find the sum of the series upto n terms Write a program to calculate the sum of series up to n
term. For example, if n =5 the series will become 2 + 22 + 222 + 2222 + 22222 = 24690
In [53]:
n=5
x=2
result=0
for i in range(1,6):
y=str(x)*i
z=int("".join(y))
#print(z)
result=result+z
#type(z)
print(result)
24690
In [119]:
for i in range(n+1,1,-1):
for j in range(1,i):
print("*",end=" ")
print("\n")
* * * *
* * *
* *
In [25]:
for i in range(1,n+1):
for j in range(1,i+1):
print("*",end=" ")
print("\r")
Excercise 65
In [26]:
for i in range(0,n):
for j in range(0,n-i):
print(end=" ")
for k in range(0,i+1):
print("*",end=" ")
print()
*
* *
* * *
* * * *
* * * * *
Exercise 66: Print the following pattern Write a program to print the following start pattern using the for loop
In [71]:
for i in range(1,n+1):
for j in range(1,i+1):
print("*",end=" ")
print("\n")
for i in range(n-1,0,-1):
for j in range(0,i):
print("*",end=" ")
print("\n")
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
Excercise 67: Write a program that keeps on accepting a number from the user until the user enters Zero.
Display the sum and average of all the numbers.
In [29]:
total=0
avg=0
count=0
while True:
if n != 0:
total=total+n
count +=1
avg=total/count
n=int(input("print another number: "))
else:
print("Thank you")
break
In [66]:
# i dont know how many time loop will run--> while loop
flag=0
i=1
odd_list=[]
while True:
if i%2 != 0:
odd_list.append(i)
flag=flag+1
if flag==25:
break
i=i+1
print(odd_list)
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 3
9, 41, 43, 45, 47, 49]
Exercise 69: Write a function called exponent(base, exp) that returns an int value of base raises to the power
of exp. Note here exp is a non-negative integer, and the base is an integer.
In [102]:
def exponent(base,exp):
result=pow(base,exp)
print(result)
exponent(10,2)
100
Exercise 70: Create a function in Python Write a program to create a function that takes two arguments,
name and age, and print their value.
In [98]:
def biodata(name,age):
print("Name of the person is {} and age is {}".format(name,age))
biodata("Milind",26)
Exercise 71: Check if the first and last number of a list is the same Write a function to return True if the first
and last number of a given list is same. If numbers are different then return False.
In [97]:
l1=[1,2,3,4,5,1]
num1=l1[0]
num2=l1[-1]
def xyz(list):
if num1==num2:
return True
else:
return False
xyz(l1)
Out[97]:
True
Given two integer numbers return their product only if the product is equal to or lower than 1000, else return
their sum.
In [14]:
def mul_sum_int(num1,num2):
#calculate product of two number
mul=num1*num2
total=num1+num2
#checking if product is less than 1000
if mul<=1000:
return mul
else:
return total
print(mul_sum_int(num1,num2))
Write a program to create function func1() to accept a variable length of arguments and print their value.
Note: Create a function in such a way that we can pass any number of arguments to this function, and the
function should process them and display each argument’s value.
In [81]:
def inputs(*num):
return num
In [82]:
inputs(45,67,78)
Out[82]:
In [76]:
inputs(34,56)
(34, 56)
Write a program to create function calculation() such that it can accept two variables and calculate addition
and subtraction. Also, it must return both addition and subtraction in a single return call.
In [79]:
def add_sub(n1,n2):
x1=n1+n2
x2=n1-n2
return x1,x2
In [80]:
add_sub(40,10)
Out[80]:
(50, 30)
Exercise 75: Create a function with a default argument Write a program to create a function
show_employee() using the following conditions.
It should accept the employee’s name and salary and display both. If the salary is missing in the function call
then assign default value 9000 to salary
In [83]:
def show_employee(name,salary="9000"):
print("name of employee is {} and his\her salary is {}".format(name,salary))
In [85]:
show_employee("milind",78686)
In [86]:
show_employee("Vishal")
In [ ]:
Exercise 76: Create an inner function to calculate the addition in the following way
Create an inner function inside an outer function that will calculate the addition of a and b
In [107]:
def outerfunc(n1,n2):
def innerfunc(n1,n2):
return n1+n2
add=innerfunc(n1,n2)
return add+5
In [108]:
outerfunc(5,10)
Out[108]:
20
In [ ]:
A] Write a program to create a recursive function to calculate the sum of numbers from 0 to 10.
Expected Output:
55
In [134]:
def addition(num):
if num==0:
return 0
else:
return num+addition(num-1)
In [135]:
addition(10)
Out[135]:
55
B] Write a program to create a recursive function to calculate the factorial of numbers from 0 to 10.
Expected Output:
120
In [132]:
def factorial(num):
if (num==1):
return 1
else:
return num*factorial(num-1)
In [133]:
factorial(5)
Out[133]:
120
Exercise 78: Assign a different name to function and call it through the new name
Below is the function display_student(name, age). Assign a new name show_student(name, age) to it and
call it using the new name.
In [141]:
def display_student(name,age):
print("name of student {} and his age is {}".format(name,age))
show_student=display_student
In [143]:
show_student("Mihir",29)
Exercise 79: Generate a Python list of all the even numbers between 4 to 30
In [145]:
for i in range(4,31):
if i%2==0:
print(i,end=" ")
4 6 8 10 12 14 16 18 20 22 24 26 28 30
In [146]:
# another way
list(range(4,31,2))
Out[146]:
[4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30]
In [157]:
y=0
for i in x:
if i > y:
y=i
print(y)
65
In [77]:
a=23
new=[]
for i in range(1,a+1):
if a%i==0:
new.append(i)
if len(new)>2:
print("it's not a prime number")
else:
print("it's prime number")
In [78]:
def is_prime(x):
new=[]
if x<=1:
return false
else:
for i in range(1,x+1):
if x%i==0:
new.append(i)
#print(new)
if len(new)<=2:
return True
else:
return False
while count<25:
if is_prime(num)==True:
print(num,end=" ")
count+=1
num+=1
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
In [79]:
def fibonacci(n):
a=0
b=1
count=0
if n<=0:
print("You can enter only Positive integer values")
elif n==1:
print(a)
else:
while count<n:
print(a,end=' ')
c=a+b
a=b
b=c
count+=1
fibonacci(n)
In [95]:
x=sentence.count("radha")
print(x)
Exercise 84: Print characters from a string that are present at an even index number Write a program to
accept a string from the user and display characters that are present at an even index number.
For example, str = "pynative" so you should display ‘p’, ‘n’, ‘t’, ‘v’.
In [93]:
x=list(string)
print(string)
for i in x[0::2]:
print(i,end=" ")
Exercise 85: Remove first n characters from a string Write a program to remove characters from a string
starting from zero up to n and return a new string.
For example:
remove_chars("pynative", 4) so output must be tive. Here we need to remove first four characters from a
string. remove_chars("pynative", 2) so output must be native. Here we need to remove first two characters
from a string. Note: n must be less than the length of the string.
In [94]:
x=len(word)
p=list(word)
for i in p:
if n<=x:
z=word[n:]
print(z)
remove("pynative",2)
native
Exercise 86 1A: Create a string made of the first, middle and last character
Write a program to create a new string made of an input string’s first, middle, and last character.
In [186]:
name="james"
a=name[0]
print(a)
c=name[-1]
print(c)
l=len(name)
x=int(l//2)
b=name[x]
print(b)
"".join([a,b,c])
j
s
m
Out[186]:
'jms'
Write a program to create a new string made of the middle three characters of an input string.
ex.JaSonAy-->Son
JhonDipPeta -->Dip
In [193]:
name="JaSonAy"
l=len(name)
if l%2==0:
print("not possible")
else:
c=l//2
x=name[c-1]
y=name[c]
z=name[c+1]
result="".join([x,y,z])
print(result)
Son
Excercise 87 :Count the frequency of a particular character in a provided string. Eg 'hello how are you' is the
string, the frequency of h in this string is 2.
In [83]:
count=0
for i in a:
if i in b:
count=count+1
In [84]:
print(a.index(b))
Excercise 89 Write a program which can remove a particular character from a string.
In [85]:
a=a.replace(b,"")
print(a)
Given two strings, s1 and s2. Write a program to create a new string s3 by appending s2 in the middle of s1.
s1 = "Ault"
s2 = "Kelly"
expected-->AuKellylt
In [206]:
s1="Ault"
s2="Kelly"
l=len(s1)
mid=l//2
f=s1[:mid]
s=s1[mid:]
s3=f+s2+s
print(s3)
AuKellylt
Exercise 91: Create a new string made of the first, middle, and last characters of each input string
Given two strings, s1 and s2, write a program to return a new string made of s1 and s2’s first, middle, and
last characters.
s1 = "America"
s2 = "Japan"
Expected output-->AJrpan
In [212]:
def unite(s1,s2):
l1=len(s1)//2
a=s1[0]
b=s1[l1]
c=s1[-1]
l2=len(s2)//2
x=s2[0]
y=s2[l2]
z=s2[-1]
result="".join([a,x,b,y,c,z])
return result
In [213]:
unite("america","japan")
Out[213]:
'ajrpan'
Exercise 92: Arrange string characters such that lowercase letters should come first
Given string contains a combination of the lower and upper case letters. Write a program to arrange the
characters of a string so that all lowercase letters should come first.
given-->PyNaTive
expected-->yaivePNT
In [223]:
string="PyNaTive"
cap=list(string.upper())
sma=list(string.lower())
new=[]
l1=list(string)
for i in l1:
if i in sma:
new.append(i)
for i in l1:
if i in cap:
new.append(i)
result="".join(new)
print(result)
yaivePNT
Exercise 93: Count all letters, digits, and special symbols from a given string
given-->str1 = "P@#yn26at^&i5ve"
In [231]:
str1 = "P@#yn26at^&i5ve"
l1=list(str1)
char=0
digit=0
special_char=0
for i in l1:
if i.isalpha()==True:
char+=1
elif i.isdigit()==True:
digit+=1
else:
special_char+=1
print("char",char)
print("digit",digit)
print("special_char",special_char)
char 8
digit 3
special_char 4
Given two strings, s1 and s2. Write a program to create a new string s3 made of the first char of s1, then the
last char of s2, Next, the second char of s1 and second last char of s2, and so on. Any leftover chars go at
the end of the result.
In [235]:
s1="ABC"
s2="xyz"
a=s1[0]
b=s1[len(s1)//2]
c=s1[-1]
x=s2[0]
y=s2[len(s2)//2]
z=s2[-1]
result="".join([a,z,b,y,c,x])
print(result)
AzByCx
Write a program to check if two strings are balanced. For example, strings s1 and s2 are balanced if all the
characters in the s1 are present in s2. The character’s position doesn’t matter.
In [239]:
s1 = "Yn"
s2 = "PYnative"
count=0
for i in s1:
if i in s2:
count+=1
if len(s1)==count:
print("s1 and s2 are balanced")
else:
print("s1 and s2 are not balanced")
Exercise 96: Find all occurrences of a substring in a given string by ignoring the case Write a program to find
all occurrences of “USA” in a given string ignoring the case.
In [242]:
str2=str1.upper()
print(str2)
str2.count("USA")
Out[242]:
Excercise 97 Write a python program to convert a string to title case without using the title()
In [87]:
b=a.split()
r=''
#print(b)
for i in b:
r=r+i.capitalize()+" "
print(r)
Exercise 98: Calculate the sum and average of the digits present in a string Given a string s1, write a
program to return the sum and average of the digits that appear in the string, ignoring all other characters.
In [254]:
str1 = "PYnative29@#8496"
str2=list(str1)
total=0
counter=0
for i in str2:
if i.isdigit()==True:
total=total+int(i)
counter+=1
str1 = "PYnative"
expected-->evitanYP
In [255]:
str1 = "PYnative"
str1[::-1]
Out[255]:
'evitanYP'
Write a program to find the last position of a substring “Emma” in a given string.
str1 = "Milind is a data scientist who knows Python. Milind works at google."
In [256]:
str1 = "Milind is a data scientist who knows Python. Milind works at google."
str1.rfind("Milind",2)
Out[256]:
45
Write a program to split a given string on hyphens and display each substring.
str1 = Emma-is-a-data-scientist
Emma
is
data
scientist
In [258]:
str1 = "Emma-is-a-data-scientist"
str2=str1.split("-")
for i in str2:
print(i)
Emma
is
a
data
scientist
In [260]:
for i in str_list:
if i == "" or i==None:
str_list.remove(i)
print(str_list)
In [269]:
import re
clean_sentence=re.sub('[^A-Za-z0-9\s]+',"",sentence)
print(clean_sentence)
expected-->2510
In [284]:
str2=str1.split()
new=[]
for i in str2:
if i.isdigit()==True:
new.append(i)
print("".join(new))
2610
Write a program to find words with both alphabets and numbers from an input string.
In [308]:
#isalnum()
str2=str1.split()
new=[]
for i in str2:
for j in i:
if j.isdigit()==True:
if i not in new:
new.append(i)
print(new[0:])
['Emma253', 'scientist50000']
Exercise 106: Replace each special symbol with # in the following string
In [324]:
import string
for i in string.punctuation:
if i in str1:
str1=str1.replace(i,"#")
print(str1)
In [1]:
emaillist=["KSR@datavizion.com","mymail@yahoo.com","milindmali@google.com","snehal@health
In [2]:
for i in emaillist:
i=i.replace("@",".").split(".")
print(i[1])
datavizion
yahoo
google
healthcare
exercies 108: extract all the emailid for the given string
In [3]:
string="Hi my name is Govind Das and my mail id is milindmali108@gmail.com and my org mai
In [4]:
new=list(string.split())
for i in new:
if ".com" in i:
print(i)
milindmali108@gmail.com
milind@google.com
In [ ]:
Given two lists, l1 and l2, write a program to create a third list l3 by picking an odd-index element from the list
l1 and even index elements from the list l2.
In [335]:
l3=[]
for i in l1[1::2]:
l3.append(i)
for i in l2[0::2]:
l3.append(i)
print(l3)
Write a program to remove the item present at index 4 and add it to the 2nd position and at the end of the
list.
List After removing element at index 4 [34, 54, 67, 89, 43, 94]
List after Adding element at index 2 [34, 54, 11, 67, 89, 43, 94]
List after Adding element at last [34, 54, 11, 67, 89, 43, 94, 11]
In [351]:
list1.pop(4)
list1.insert(2,11)
list1.append(11)
print(list1)
Exercise 111: Slice list into 3 equal chunks and reverse each chunk
In [2]:
sample_list = [11,49,8,23,14,12,78,45,89]
n=int(len(sample_list)/3)
l1=sample_list[0:n]
l2=sample_list[n:n*2]
l3=sample_list[n*2:n*3]
print("chunk 1",l1)
print("Reversed of chunk 1",l1[::-1])
print("chunk 2",l2)
print("Reversed of chunk 2",l2[::-1])
print("chunk 3",l3)
print("Reversed of chunk 3",l3[::-1])
Write a program to iterate a given list and count the occurrence of each element and create a dictionary to
show the count of each element.
Expected Output:--> Printing count of each item {11: 2, 45: 3, 8: 1, 23: 2, 89: 1}
In [7]:
count=dict()
for i in list1:
if i in count:
count[i]+=1
else:
count[i]=1
print(count)
Exercise 113: Create a Python set such that it shows the element from both lists in a pair
first_list = [2, 3, 4, 5, 6, 7, 8]
Result is {(6, 36), (8, 64), (4, 16), (5, 25), (3, 9), (7, 49), (2, 4)}
In [10]:
first_list = [2, 3, 4, 5, 6, 7, 8]
result=zip(first_list,second_list)
result_set=set(result)
print(result_set)
{(7, 49), (2, 4), (4, 16), (8, 64), (6, 36), (3, 9), (5, 25)}
Exercise 114: Find the intersection (common) of two sets and remove those elements from the first set
First Set after removing common element {65, 42, 78, 23}
In [20]:
intersection=first_set.intersection(second_set)
print(intersection)
for i in intersection:
first_set.remove(i)
print(first_set)
Exercise 115: Checks if one set is a subset or superset of another set. If found, delete all elements from that
set
expected output:
In [31]:
if first_set.issubset(second_set):
first_set.clear()
if second_set.issubset(first_set):
second_set.clear()
print("first set:\n",first_set)
print("second set:\n",second_set)
Exercise 116: Iterate a given list and check if a given element exists as a key’s value in a dictionary. If not,
delete it from the list
Expected result:--> After removing unwanted elements from list [47, 69, 76, 97]
In [36]:
print(roll_number)
Exercise 117: Get all values from the dictionary and add them to a list but don’t add duplicates
speed = {'jan': 47, 'feb': 52, 'march': 47, 'April': 44, 'May': 52, 'June': 53, 'july': 54, 'Aug': 44, 'Sept': 54}
In [37]:
speed = {'jan': 47, 'feb': 52, 'march': 47, 'April': 44, 'May': 52, 'June': 53, 'july': 5
speed_list=[]
print(speed_list)
Exercise 118: Remove duplicates from a list and create a tuple and find the minimum and maximum number
Expected-->
min: 41
max: 99
In [43]:
tuple1=tuple(list1)
Excercise: 119 Write a python program to find the max item from a list without using the max function
In [88]:
l1=[4,6,2,8,1]
l1.sort(reverse=True)
print(l1[0])
Excercise 120 Find the reverse of a number provided by the user(any number of digit)
In [82]:
digit_list=list(map(int,str(n)))
digit_list=digit_list[::-1]
num=int("".join(map(str,digit_list)))
print(num)
Excercise 121 Take a number from the user and find the number of digits in it.
In [80]:
digit_list=list(map(int,str(n)))
print(digit_list)
print(len(digit_list))
Exercise 122: Write a python program to remove all the duplicates from a list
In [31]:
l1=[1,2,3,3,3,4,4,5,6,7,8,9,9]
l2=[]
for i in l1:
if i not in l2:
l2.append(i)
print(l2)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
In [49]:
print(list1[::-1])
Write a program to add two lists index-wise. Create a new list that contains the 0th index item from both the
list, then the 1st index item, and so on till the last element. any leftover items will get added at the end of the
new list.
expected result:
In [55]:
print(list3)
Given a list of numbers. write a program to turn every item of a list into its square.
In [58]:
numbers = [1, 2, 3, 4, 5, 6, 7]
new=[]
for i in numbers:
x=pow(i,2)
new.append(x)
print(new)
In [59]:
Expected result:
In [60]:
for i in list1:
for j in list2:
print(i+j)
Hello Dear
Hello Sir
take Dear
take Sir
In [63]:
Given a two Python list. Write a program to iterate both lists simultaneously and display items from list1 in
original order and items from list2 in reverse order.
Expected-->
10 400
20 300
30 200
In [64]:
10 400
20 300
30 200
40 100
expected:
In [76]:
result=list(filter(lambda x: x!="",list1))
print(result)
Write a program to add item 7000 after 6000 in the following Python List
list1 = [10, 20, [300, 400, [5000, 6000], 500], 30, 40]
Expected output:
[10, 20, [300, 400, [5000, 6000, 7000], 500], 30, 40]
In [78]:
list1 = [10, 20, [300, 400, [5000, 6000], 500], 30, 40]
list1[2][2].append(7000)
print(list1)
[10, 20, [300, 400, [5000, 6000, 7000], 500], 30, 40]
You have given a nested list. Write a program to extend it by adding the sublist ["h", "i", "j"] in such a way that
it will look like the following list.
list1 = ["a", "b", ["c", ["d", "e", ["f", "g"], "k"], "l"], "m", "n"]
Expected result:
['a', 'b', ['c', ['d', 'e', ['f', 'g', 'h', 'i', 'j'], 'k'], 'l'], 'm', 'n']
In [79]:
list1 = ["a", "b", ["c", ["d", "e", ["f", "g"], "k"], "l"], "m", "n"]
list1[2][1][2].extend(sub_list)
print(list1)
['a', 'b', ['c', ['d', 'e', ['f', 'g', 'h', 'i', 'j'], 'k'], 'l'], 'm',
'n']
You have given a Python list. Write a program to find value 20 in the list, and if it is present, replace it with
200. Only update the first occurrence of an item.
In [81]:
x=list1.index(20)
list1[x]=200
print(list1)
Given a Python list, write a program to remove all occurrences of item 20.
Expected output:
In [83]:
while 20 in list1:
list1.remove(20)
print(list1)
Excercise 133 Write a python program to remove all the duplicates from a list
In [86]:
l1=[1,2,3,3,3,4,4,5,6,7,8,9,9]
l2=[]
for i in l1:
if i not in l2:
l2.append(i)
print(l2)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Excercise 134 :Write a program that can perform union and intersection on 2 given list.
In [90]:
l1=[1,2,3,4,5]
l2=[4,5,6,7,8]
uni=[]
inter=[]
for i in l1:
if i in l2:
inter.append(i)
print(inter)
for i in l1:
if i not in uni:
uni.append(i)
for i in l2:
if i not in uni:
uni.append(i)
print(uni)
[4, 5]
[1, 2, 3, 4, 5, 6, 7, 8]
Below are the two lists. Write a Python program to convert them into a dictionary in a way that item from list1
is the key and item from list2 is the value
Expected output:
In [85]:
my_dict=zip(keys,values)
result=dict(my_dict)
print(result)
Expected output
{'Ten': 10, 'Twenty': 20, 'Thirty': 30, 'Fourty': 40, 'Fifty': 50}
In [86]:
dict3={**dict1,**dict2}
print(dict3)
{'Ten': 10, 'Twenty': 20, 'Thirty': 30, 'Fourty': 40, 'Fifty': 50}
In [92]:
dict3=dict1.copy()
dict3.update(dict2)
print(dict3)
{'Ten': 10, 'Twenty': 20, 'Thirty': 30, 'Fourty': 40, 'Fifty': 50}
Exercise 137: Print the value of key ‘history’ from the below dict
expected output: 80
In [107]:
sampleDict["class"]["student"]["marks"]["history"]
Out[107]:
80
Exercise 138: Initialize dictionary with default values In Python, we can initialize the keys with the same
values.
expected output: {'Kelly': {'designation': 'Developer', 'salary': 8000}, 'Emma': {'designation': 'Developer',
'salary': 8000}}
In [116]:
result=dict.fromkeys(employees,defaults)
print(result)
print("="*100)
print("Details of kelly: ",result["Kelly"])
Exercise 139: Create a dictionary by extracting the keys from a given dictionary
Write a Python program to create a new dictionary by extracting the mentioned keys from the below
dictionary.
sample_dict = { "name": "Kelly", "age": 25, "salary": 8000, "city": "New york"}
expected output:
In [120]:
sample_dict = {
"name": "Kelly",
"age": 25,
"salary": 8000,
"city": "New york"}
keys=["name","salary"]
result=dict()
for k in keys:
result.update({k:sample_dict[k]})
print(result)
In [124]:
keys=["name","salary"]
print(new_dict)
We know how to check if the key exists in a dictionary. Sometimes it is required to check if the given value is
present.
Write a Python program to check if value 200 exists in the following dictionary.
given:
expected:
In [125]:
if 200 in sample_dict.values():
print("200 is present in given dict")
expected:
In [126]:
sample_dict = {
"name": "Kelly",
"age":25,
"salary": 8000,
"city": "New york"
}
sample_dict["location"]=sample_dict.pop("city")
print(sample_dict)
Exercise 142: Get the key of a minimum value from the following dictionary
Expected:
math
In [129]:
sample_dict = {
'Physics': 82,
'Math': 65,
'history': 75
}
list1=[]
min(sample_dict,key=sample_dict.get)
Out[129]:
'Math'
Write a Python program to change Brad’s salary to 8500 in the following dictionary.
sample_dict = { 'emp1': {'name': 'Jhon', 'salary': 7500}, 'emp2': {'name': 'Emma', 'salary': 8000}, 'emp3':
{'name': 'Brad', 'salary': 500} }
expected output:
{ 'emp1': {'name': 'Jhon', 'salary': 7500}, 'emp2': {'name': 'Emma', 'salary': 8000}, 'emp3': {'name': 'Brad',
'salary': 8500} }
In [130]:
sample_dict = {
'emp1': {'name': 'Jhon', 'salary': 7500},
'emp2': {'name': 'Emma', 'salary': 8000},
'emp3': {'name': 'Brad', 'salary': 500}
}
sample_dict["emp3"]["salary"]=8500
print(sample_dict)
Given a Python list, Write a program to add all its elements into a given set.
In [135]:
sample_set.update(sample_list)
print(sample_set)
Exercise 145: Return a new set of identical items from two sets
In [136]:
set3=set1.intersection(set2)
print(set3)
Write a Python program to return a new set with unique items from both sets by removing duplicates.
In [137]:
set3=set1.union(set2)
print(set3)
Exercise 147: Update the first set with items that don’t exist in the second set
Given two Python sets, write a Python program to update the first set with items that exist only in the first set
and not in the second set.
expected result:
In [141]:
set1.difference_update(set2)
print(set1)
{10, 30}
Write a Python program to remove items 10, 20, 30 from the following set at once.
expected:
{40, 50}
In [143]:
set2={10,20,30}
set1.difference_update(set2)
print(set1)
{50, 40}
Exercise 149: Return a set of elements present in Set A or B, but not both
Expected Output:
In [145]:
set1.symmetric_difference(set2)
Out[145]:
Exercise 150: Check if two sets have any elements in common. If yes, display the common elements
expected:
In [149]:
if set1.isdisjoint(set2):
print("above two set dont have any common element")
else:
set1.intersection(set2)
print(set1.intersection(set2))
{10}
Exercise 151: Update set1 by adding items from set2, except common items
Expected;
In [152]:
set1.symmetric_difference_update(set2)
print(set1)
Exercise 152: Remove items from set1 that are common to both set1 and set2
Expected output:
In [156]:
set1.intersection_update(set2)
set1
Out[156]:
In [157]:
tuple1[::-1]
Out[157]:
The given tuple is a nested tuple. write a Python program to print the value 20.
In [158]:
tuple1[1][1]
Out[158]:
20
In [159]:
tuple1=(50,)
print(tuple1)
(50,)
Write a program to unpack the following tuple into four variables and display each variable.
your code
In [160]:
a,b,c,d=tuple1
print(a)
print(b)
print(c)
print(d)
10
20
30
40
In [163]:
tuple1,tuple2=tuple2,tuple1
print("tuple1",tuple1)
print("tuple2",tuple2)
Exercise 158: Copy specific elements from one tuple to a new tuple Write a program to copy elements 44
and 55 from the following tuple into a new tuple.
Expected
In [164]:
tuple2=tuple1[3:5]
print(tuple2)
(44, 55)
Given is a nested tuple. Write a program to modify the first item (22) of a list inside a following tuple to 222
Expected
In [167]:
tuple1[1][0]=222
tuple1
Out[167]:
Expected:
In [175]:
tuple1=sorted(list(tuple1),key=lambda x:x[1])
tuple(tuple1)
Out[175]:
In [176]:
tuple1.count(50)
Out[176]:
Exercise 162: Check if all items in the tuple are the same
In [199]:
all_same=all(i==t[0] for i in t)
if all_same:
print("yes all the item are same in the given tuple")
else:
print("No all the item are not same in the given table")
In [201]:
import datetime
2023-05-24 15:12:07.167241
15:12:07.167241
For example, You received the following date in string format. Please convert it into Python’s DateTime
object
In [210]:
date_time_object=datetime.strptime(date_string,"%b %d %Y %I:%M%p")
print(date_time_object)
2020-02-25 16:20:00
expected date:
2020-02-18
In [212]:
print(given_date)
days_to_substract=7
res_date=given_date-timedelta(days_to_substract)
print(res_date)
2020-02-25 00:00:00
2020-02-18 00:00:00
expected:
In [217]:
given_date.strftime("%A %d %b %Y")
Out[217]:
Given:
Expected output:
Sunday
In [218]:
given_date.strftime("%A")
Out[218]:
'Sunday'
Given:
#2020-03-22 10:00:00
Expected output:
2020-03-29 22:00:00
In [221]:
days_to_add=7
res_date=given_date+timedelta(days_to_add,12)
In [222]:
import time
milliseconds=int(round(time.time()*1000))
print(milliseconds)
1684923177395
Given:
Expected output:
"2020-02-25 00:00:00"
In [227]:
string_date=given_date.strftime("%Y-%m-%d %H:%M:%S")
string_date
Out[227]:
'2020-02-25 00:00:00'
Exercise 171: Calculate the date 4 months from the current date
Given:
#2020-02-25
Expected output:
2020-06-25
In [233]:
# 2020-02-25
months_to_add=4
result_date=given_date+relativedelta(months= + months_to_add)
print(result_date)
2020-06-25
Given:
#2020-02-25
#2020-09-17
Expected output:
205 days
In [237]:
# 2020-02-25
date_1 = datetime(2020, 2, 25).date()
# 2020-09-17
date_2 = datetime(2020, 9, 17).date()
delta=None
if date_1>date_2:
delta=date_1-date_2
else:
delta=date_2-date_1
Write a Python program to create a Vehicle class with max_speed and mileage instance attributes.
In [249]:
class Vehicle:
def __init__ (self,max_speed,mileage):
self.max_speed=max_speed
self.mileage=mileage
maruti=Vehicle(120,15)
print(maruti.max_speed,maruti.mileage)
120 15
OOP Exercise 174: Create a Vehicle class without any variables and methods
In [250]:
class Vehicle:
pass
OOP Exercise 3: Create a child class Bus that will inherit all of the variables and methods of the Vehicle
class
In [252]:
class Vehicle:
def __init__ (self,max_speed,mileage):
self.max_speed=max_speed
self.mileage=mileage
class Bus(Vehicle):
pass
School_bus=Bus(70,10)
print(School_bus.max_speed,School_bus.mileage)
70 10
Given:
Create a Bus class that inherits from the Vehicle class. Give the capacity argument of Bus.seating_capacity()
a default value of 50.
In [5]:
class Vehicle:
def sitting_capacity(self,capacity):
return f"sitting capacity of bus {self.name} is {capacity} passanger"
In [6]:
class Bus(Vehicle):
#assign defualt value to capacity 50
def sitting_capacity(self,capacity=50):
return super().sitting_capacity(capacity=50)
In [14]:
School_bus=Bus("Volvo",120,23)
In [12]:
School_bus.sitting_capacity()
Out[12]:
OOP Exercise 176: Define a property that must have the same value for every class instance (object) Define
a class attribute”color” with a default value white. I.e., Every Vehicle should be white.
In [34]:
class Vehicle:
Color="White"
class Bus(Vehicle):
pass
class Car(Vehicle):
pass
In [37]:
School_bus=Bus("Volvo",120,23)
print(School_bus.name,School_bus.Color,School_bus.max_speed,School_bus.mileage)
In [39]:
Maruti=Car("Swift",90,41)
print(Maruti.name,Maruti.Color,Maruti.max_speed,Maruti.mileage)
Swift White 90 41
Create a Bus child class that inherits from the Vehicle class. The default fare charge of any vehicle is seating
capacity * 100. If Vehicle is Bus instance, we need to add an extra 10% on full fare as a maintenance charge.
So total fare for bus instance will become the final amount = total fare + 10% of the total fare.
Note: The bus seating capacity is 50. so the final fare amount should be 5500. You need to override the
fare() method of a Vehicle class in Bus class.
In [46]:
class Vehicle:
def __init__(self, name, mileage, capacity):
self.name = name
self.mileage = mileage
self.capacity = capacity
def fare(self):
return self.capacity * 100
class Bus(Vehicle):
def fare(self):
amount=super().fare()
amount+=amount*0.1
return amount
Write a program to determine which class a given Bus object belongs to.
In [47]:
class Vehicle:
def __init__(self, name, mileage, capacity):
self.name = name
self.mileage = mileage
self.capacity = capacity
class Bus(Vehicle):
pass
In [48]:
type(School_bus)
Out[48]:
__main__.Bus
In [49]:
OOP Exercise 179: Determine if School_bus is also an instance of the Vehicle class
In [50]:
class Vehicle:
def __init__(self, name, mileage, capacity):
self.name = name
self.mileage = mileage
self.capacity = capacity
class Bus(Vehicle):
pass
In [52]:
isinstance(School_bus,Vehicle)
Out[52]:
True
Expected Output:
In [59]:
import json
print(jsondata)
Exercise 181: Access the value of key2 from the following JSON
import json
Expected Output:
value2
In [60]:
data["key2"]
Out[60]:
'value2'
PrettyPrint following JSON data with indent level 2 and key-value separators should be (",", " = ").
Expected Output:
"key1" = "value1",
"key2" = "value2",
"key3" = "value3"
In [75]:
PrettyPrintedJson = json.dumps(sampleJson,indent=2,separators=(",","="))
print(PrettyPrintedJson)
{
"key1"="value1",
"key2"="value2",
"key3"="value3"
}
Exercise 183: Sort JSON keys in and write them into a file
Expected Output:
"age": 29,
"id": 1,
"name": "value2"
localhost:8889/notebooks/Desktop/Data Science/Python Practice/Milind Mali_Python Practice_200%2B.ipynb 85/122
6/7/23, 5:30 PM Milind Mali_Python Practice_200+ - Jupyter Notebook
In [78]:
Exercise 184: Access the nested key ‘salary’ from the following JSON
In [84]:
import json
sampleJson = """{
"company":{
"employee":{
"name":"emma",
"payble":{
"salary":7000,
"bonus":800
}
}
}
}"""
data=json.loads(sampleJson)
print(data["company"]["employee"]["payble"]["salary"])
7000
In [85]:
import json
class Vehicle:
def __init__(self, name, engine, price):
self.name = name
self.engine = engine
self.price = price
In [86]:
class Vehicle:
def __init__(self, name, engine, price):
self.name = name
self.engine = engine
self.price = price
class VehicleEncoder(JSONEncoder):
def default(self,o):
return o.__dict__
For example, we should be able to access Vehicle Object using the dot operator like this.
In [87]:
import json
class Vehicle:
def __init__(self, name, engine, price):
self.name = name
self.engine = engine
self.price = price
def vehicleDecoder(obj):
return Vehicle(obj['name'], obj['engine'], obj['price'])
vehicleObj = json.loads('{ "name": "Toyota Rav4", "engine": "2.5L", "price": 32000 }',
object_hook=vehicleDecoder)
Exercise 187: Check whether following json is valid or invalid. If Invalid correct it
In [90]:
{
"company": {
"employee": {
"name": "emma",
"payble": {
"salary": 7000,
"bonus": 800
}
}
}
}
Exercise 188: Parse the following JSON to get all the values of a key ‘name’ within an array
In [91]:
import json
sampleJson = """[
{
"id":1,
"name":"name1",
"color":[
"red",
"green"
]
},
{
"id":2,
"name":"name2",
"color":[
"pink",
"yellow"
]
}
]"""
data = []
try:
data = json.loads(sampleJson)
except Exception as e:
print(e)
['name1', 'name2']
In [92]:
import numpy as np
x=[[1,2,3],[4,5,6],[7,8,9]]
y=np.asarray(x)
print(y)
y.max()
[[1 2 3]
[4 5 6]
[7 8 9]]
Out[92]:
Exercise 190: Create a 4X2 integer array and Prints its attributes
Note: The element must be a type of unsigned int16. And print the following Attributes: –
In [99]:
import numpy as np
print(firstArray)
[[41232 40805]
[17953 58303]
[ 1887 4407]
[31432 20031]]
shape of the array is: (4, 2)
dimension of the array is: 2
itemsize of each element in array is: 2
Exercise 191: Create a 5X2 integer array from a range between 100 to 200 such that the difference between
each element is 10
In [104]:
my_array=np.arange(100,200,10)
my_array=my_array.reshape(5,2)
print(my_array)
[[100 110]
[120 130]
[140 150]
[160 170]
[180 190]]
Exercise 192: Following is the provided numPy array. Return array of items by taking the third column from
all rows
sampleArray = numpy.array([[11 ,22, 33], [44, 55, 66], [77, 88, 99]])
In [112]:
sampleArray = np.array([[11 ,22, 33], [44, 55, 66], [77, 88, 99]])
#print(sampleArray)
new_array=sampleArray[...,2]
print(new_array)
[33 66 99]
Exercise 193: Return array of odd rows and even columns from below numpy array
sampleArray = numpy.array([[3 ,6, 9, 12], [15 ,18, 21, 24], [27 ,30, 33, 36], [39 ,42, 45, 48], [51 ,54, 57, 60]])
In [113]:
print(sampleArray)
[[ 3 6 9 12]
[15 18 21 24]
[27 30 33 36]
[39 42 45 48]
[51 54 57 60]]
In [115]:
new_array=sampleArray[::2,1::2]
print(new_array)
[[ 6 12]
[30 36]
[54 60]]
Exercise 194: Create a result array by adding the following two NumPy arrays. Next, modify the result array
by calculating the square of each element
In [122]:
#print(arrayOne)
#print(arrayTwo)
result_array=arrayOne+arrayTwo
print(result_array)
final_output=pow(result_array,2)
print(final_output)
[[20 39 33]
[25 25 28]]
[[ 400 1521 1089]
[ 625 625 784]]
Note: Create an 8X3 integer array from a range between 10 to 34 such that the difference between each
element is 1 and then Split the array into four equal-sized sub-arrays.
In [129]:
new_array=np.arange(10,34,1)
new_array=new_array.reshape(8,3)
print(new_array)
subarray=np.split(new_array,4)
print("="*100)
print(subarray)
[[10 11 12]
[13 14 15]
[16 17 18]
[19 20 21]
[22 23 24]
[25 26 27]
[28 29 30]
[31 32 33]]
==========================================================================
==========================
[array([[10, 11, 12],
[13, 14, 15]]), array([[16, 17, 18],
[19, 20, 21]]), array([[22, 23, 24],
[25, 26, 27]]), array([[28, 29, 30],
[31, 32, 33]])]
sampleArray = numpy.array([[34,43,73],[82,22,12],[53,94,66]])
In [132]:
sampleArray = np.array([[34,43,73],[82,22,12],[53,94,66]])
print(sampleArray)
[[34 43 73]
[82 22 12]
[53 94 66]]
Sorting Original array by secoond row
[[73 43 34]
[12 22 82]
[66 94 53]]
Sorting Original array by second column
[[82 22 12]
[34 43 73]
[53 94 66]]
Exercise 197: Print max from axis 0 and min from axis 1 from the following 2-D array.
sampleArray = numpy.array([[34,43,73],[82,22,12],[53,94,66]])
In [134]:
import numpy
minOfAxisOne = numpy.amin(sampleArray, 1)
print("Printing amin Of Axis 1")
print(minOfAxisOne)
maxOfAxisOne = numpy.amax(sampleArray, 0)
print("Printing amax Of Axis 0")
print(maxOfAxisOne)
Exercise 198: Delete the second column from a given array and insert the following new column in its place.
sampleArray = numpy.array([[34,43,73],[82,22,12],[53,94,66]])
newColumn = numpy.array([[10,10,10]])
In [135]:
import numpy
arr = numpy.array([[10,10,10]])
In [5]:
import pandas as pd
In [6]:
df=pd.read_csv("iris_data.csv")
In [7]:
df.head()
Out[7]:
In [8]:
df=df.drop("Id",axis=1)
In [9]:
df.head()
Out[9]:
In [10]:
In [13]:
df["species"]=df["species"].str.replace("Iris-","")
In [14]:
df.head()
Out[14]:
In [15]:
Out[15]:
(150, 5)
In [16]:
Out[16]:
In [17]:
Out[17]:
setosa 50
versicolor 50
virginica 50
Name: species, dtype: int64
In [18]:
#how many rows are there whose sepal length is greater than its mean
(df["sepal_length"]>df["sepal_length"].mean()).sum()
# 70 rows are there whose sepal length is greater than avg sepal length
Out[18]:
70
In [19]:
#extract all the rows whose petal width is greater than 1.5 and petal length is lesser t
df[(df["petal_width"]>1.5) & (df["petal_length"]<5)]
Out[19]:
In [20]:
df["sepal_length"].max()
Out[20]:
7.9
In [21]:
df[df["sepal_length"]==df["sepal_length"].max()]
Out[21]:
In [22]:
#extract mean median of sepal lenth,sepal width ,petal lenth , petal width for all the sp
In [23]:
df.groupby("species").agg(["mean","median"])
Out[23]:
species
Excercise 200
In [105]:
import pandas as pd
In [106]:
df = pd.read_csv("Automobile_data.csv", na_values={
'price':["?","n.a"],
'stroke':["?","n.a"],
'horsepower':["?","n.a"],
'peak-rpm':["?","n.a"],
'average-mileage':["?","n.a"]})
df
Out[106]:
... ... ... ... ... ... ... ... ... ...
61 rows × 10 columns
Exercise 200: From the given dataset print the first and last five rows
In [107]:
df.head()
Out[107]:
alfa-
0 0 convertible 88.6 168.8 dohc four 111 21 134
romero
alfa-
1 1 convertible 88.6 168.8 dohc four 111 21 165
romero
alfa-
2 2 hatchback 94.5 171.2 ohcv six 154 19 165
romero
In [186]:
missing_value=["?","n.a",np.NaN]
df=pd.read_csv("Automobile_data.csv",na_values=missing_value)
In [187]:
df.isnull().sum()
Out[187]:
index 0
company 0
body-style 0
wheel-base 0
length 0
engine-type 0
num-of-cylinders 0
horsepower 0
average-mileage 0
price 3
dtype: int64
In [189]:
df.isnull().sum()
Out[189]:
index 0
company 0
body-style 0
wheel-base 0
length 0
engine-type 0
num-of-cylinders 0
horsepower 0
average-mileage 0
price 3
dtype: int64
In [190]:
df=df.drop("index",axis=1)
In [191]:
df["price"].max()
Out[191]:
45400.0
In [192]:
most_exp_car=df[["company","price"]][df.price==df["price"].max()]
most_exp_car
Out[192]:
company price
35 mercedes-benz 45400.0
In [201]:
df.groupby("company").get_group("toyota")
Out[201]:
In [202]:
df["company"].value_counts()
Out[202]:
toyota 7
bmw 6
mazda 5
nissan 5
audi 4
mercedes-benz 4
mitsubishi 4
volkswagen 4
alfa-romero 3
chevrolet 3
honda 3
isuzu 3
jaguar 3
porsche 3
dodge 2
volvo 2
Name: company, dtype: int64
In [211]:
import warnings
warnings.filterwarnings("ignore")
In [220]:
df.groupby("company")[["company","price"]].max()
Out[220]:
company price
company
Exercise 204: Find the average mileage of each car making company
In [221]:
df.groupby("company")[["company","average-mileage"]].mean()
Out[221]:
average-mileage
company
alfa-romero 20.333333
audi 20.000000
bmw 19.000000
chevrolet 41.000000
dodge 31.000000
honda 26.333333
isuzu 33.333333
jaguar 14.333333
mazda 28.000000
mercedes-benz 18.000000
mitsubishi 29.500000
nissan 31.400000
porsche 17.000000
toyota 28.714286
volkswagen 31.750000
volvo 23.000000
In [223]:
df.sort_values("price",ascending=False)
Out[223]:
mercedes-
35 hardtop 112.0 199.2 ohcv eight 184 14 45400.0
benz
mercedes-
34 sedan 120.9 208.1 ohcv eight 184 14 40960.0
benz
... ... ... ... ... ... ... ... ... ...
61 rows × 9 columns
Exercise 206: Concatenate two data frames using the following conditions
In [224]:
In [225]:
germanCar=pd.DataFrame.from_dict(GermanCars)
In [226]:
germanCar
Out[226]:
Company Price
0 Ford 23845
1 Mercedes 171995
2 BMV 135925
3 Audi 71400
In [227]:
japaneseCar=pd.DataFrame.from_dict(japaneseCars)
japaneseCar
Out[227]:
Company Price
0 Toyota 29995
1 Honda 23600
2 Nissan 61500
3 Mitsubishi 58900
In [229]:
carsDF=pd.concat([germanCar,japaneseCar],keys=["germany","Japan"])
carsDF
Out[229]:
Company Price
0 Ford 23845
1 Mercedes 171995
germany
2 BMV 135925
3 Audi 71400
0 Toyota 29995
1 Honda 23600
Japan
2 Nissan 61500
3 Mitsubishi 58900
Exercise 207: Merge two data frames using the following condition
In [230]:
Car_Price = {'Company': ['Toyota', 'Honda', 'BMV', 'Audi'], 'Price': [23845, 17995, 13592
car_Horsepower = {'Company': ['Toyota', 'Honda', 'BMV', 'Audi'], 'horsepower': [141, 80,
In [232]:
carPrice=pd.DataFrame.from_dict(Car_Price)
carPrice
Out[232]:
Company Price
0 Toyota 23845
1 Honda 17995
2 BMV 135925
3 Audi 71400
In [233]:
carHorsepower=pd.DataFrame.from_dict(car_Horsepower)
carHorsepower
Out[233]:
Company horsepower
0 Toyota 141
1 Honda 80
2 BMV 182
3 Audi 160
In [234]:
carsDF=pd.merge(carPrice,carHorsepower,on="Company")
carsDF
Out[234]:
1 Honda 17995 80
Total profit data provided for each month. Generated line plot must include the following properties: –
In [9]:
import pandas as pd
import matplotlib.pyplot as plt
sales_data=pd.read_csv("company_sales_data.csv")
sales_date.head()
Out[9]:
In [21]:
import numpy as np
In [33]:
monthList=sales_data["month_number"].tolist()
profitList=np.arange(100000,500000,50000).tolist()
In [36]:
plt.plot("month_number","total_profit",data=sales_data)
plt.xlabel("Month Number")
plt.xticks(monthList)
plt.yticks(profitList)
plt.ylabel("Total profit")
plt.title("COMPANY PROFIT PER MONTH")
plt.show()
Exercise 209: Get total profit of all months and show line plot with the following Style properties Generated
line plot must include following Style properties: –
In [58]:
plt.plot("month_number","total_profit",data=sales_data,color="red", marker='o',markerface
linewidth=2, markersize=6)
plt.xlabel("Month Number")
plt.xticks(monthList)
plt.ylabel("Total Profit")
plt.yticks(profitList)
plt.legend(loc="upper left")
plt.title("COMPANY SALES FOR LAST YEAR")
plt.show()
Exercise 210: Read all product sales data and show it using a multiline plot Display the number of units sold
per month for each product using multiline plots. (i.e., Separate Plotline for each product ).
In [59]:
sales_data.head()
Out[59]:
In [91]:
quantityList=np.arange(1000,20000,2000)
In [92]:
plt.plot("month_number","facecream",data=sales_data,marker="o")
plt.plot("month_number","facewash",data=sales_data,marker="o")
plt.plot("month_number","toothpaste",data=sales_data,marker="o")
plt.plot("month_number","bathingsoap",data=sales_data,marker="o")
plt.plot("month_number","shampoo",data=sales_data,marker="o")
plt.plot("month_number","moisturizer",data=sales_data,marker="o")
plt.xticks(monthList)
plt.xlabel("Month Number")
plt.yticks(quantityList)
plt.ylabel("Sales of product in number of units")
plt.legend(loc="upper left")
plt.show()
#since column values for facewash and moisturizer are same line plot is overlapping each other
Exercise 211: Read toothpaste sales data of each month and show it using a scatter plot Also, add a grid in
the plot. gridline style should “–“.
In [103]:
plt.scatter("month_number","toothpaste",data=sales_data)
plt.legend(loc="upper left")
plt.grid(color='r', linestyle='dashed', linewidth=0.5)
plt.xlabel("Month Number")
plt.ylabel("Quantity Sales")
plt.show()
Exercise 212: Read face cream and facewash product sales data and show it using the bar chart
The bar chart should display the number of units sold per month for each product. Add a separate bar for
each product in the same chart.
In [129]:
plt.xticks(monthList)
plt.xlabel("Month Number")
plt.ylabel("quantity sales")
plt.legend()
plt.grid(color='r', linestyle='dashed', linewidth=0.5)
plt.show()
Exercise 213: Read sales data of bathing soap of all months and show it using a bar chart. Save this plot to
your hard disk
In [139]:
plt.bar("month_number","total_units",data=sales_data)
plt.grid(True,linestyle="dashed")
plt.xticks(monthList)
plt.xlabel("Month Number")
plt.ylabel("Sales units in numbers")
plt.title("Bath soaping sales data")
plt.show()
Exercise 214: Read the total profit of each month and show it using the histogram to see the most common
profit ranges
In [144]:
profitList=df["total_profit"].tolist()
In [151]:
profit_range=np.arange(150000,350000,25000)
In [156]:
Exercise 8: Calculate total sale data for last year for each product and show it using a Pie chart
In [174]:
sales_data.head(2)
Out[174]:
In [159]:
saleData=[df["facecream"].sum(),df["facewash"].sum(),df["toothpaste"].sum(),df["bathingso
saleData
Out[159]:
In [169]:
In [173]:
plt.pie(saleData,autopct="%1.1f%%",labels=labels)
plt.legend()
plt.show()
Exercise 215: Read Bathing soap and facewash of all months and display it using the Subplot
In [198]:
plt.subplot(2,1,1)
plt.plot("month_number","bathingsoap",data=sales_data,color="black",marker="o")
plt.title("sales data of bathing soap")
plt.subplot(2,1,2)
plt.plot("month_number","facewash",data=sales_data,color="red",marker="o")
plt.xlabel("Month Number")
plt.title("sales data of facewash")
plt.ylabel("sales units in numbers")
plt.subplots_adjust(bottom=0.1,wspace=0.4,hspace=0.3)
plt.show()
In [205]:
import random
print("generating three digit number from 100 to 999 which id divisible by 5")
for i in range(3):
print(random.randrange(100,999,5))
Exercise 217: Random Lottery Pick. Generate 100 random lottery tickets and pick two lucky tickets from it as
a winner. Note you must adhere to the following conditions:
In [200]:
import random
lottery_tickets_list = []
print("creating 100 random lottery tickets")
# to get 100 ticket
for i in range(100):
# ticket number must be 10 digit (1000000000, 9999999999)
lottery_tickets_list.append(random.randrange(1000000000, 9999999999))
# pick 2 luck tickets
winners = random.sample(lottery_tickets_list, 2)
print("Lucky 2 lottery tickets are", winners)
In [202]:
import secrets
OTPgenerator=secrets.SystemRandom()
otp=OTPgenerator.randrange(100000,999999)
In [207]:
name="Milind Mali"
char=random.choice(name)
print(char)
Exercise 220: Generate random String of length 5 Note: String must be the combination of the UPPER case
and lower case letters only. No numbers and a special symbol.
In [209]:
import random
import string
def randomstring(stringLength):
"""gernerate random string of five characters"""
letters=string.ascii_letters
return "".join(random.choice(letters) for i in range(stringLength))
Exercise 221: Generate a random Password which meets the following conditions Password length must be
10 characters long.
It must contain at least 2 upper case letters, 1 digit, and 1 special symbol.
In [212]:
import random
import string
def randomPassword():
randomSource=string.ascii_letters+string.digits+string.punctuation
password=random.sample(randomSource,6)
password+=random.sample(string.ascii_uppercase,2)
password+=random.choice(string.digits)
password+=random.choice(string.punctuation)
passwordList=list(password)
random.SystemRandom().shuffle(passwordList)
password="".join(passwordList)
return password
First random float number must be between 0.1 and 1 Second random float number must be between 9.5
In [215]:
num1=random.random()
num2=random.uniform(9.5,99.5)
num3=num1+num2
print(num3)
10.93030484756581
Exercise 223: Generate random secure token of 64 bytes and random URL
In [216]:
import secrets
Exercise 224: Roll dice in such a way that every time you get the same number
Dice has 6 numbers (from 1 to 6). Roll dice in such a way that every time you must get the same output
number. do this 5 times.
In [218]:
import random
dice = [1, 2, 3, 4, 5, 6]
print("Randomly selecting same number of a dice")
for i in range(5):
random.seed(25)
print(random.choice(dice))
Exercise 225: Generate a random date between given start and end dates
In [219]:
import random
import time