Adp Programs
Adp Programs
1.Programs on Operators
A) Read a list of numbers and write a program to check whether a particular element is present or not
using membership operators.
Program:
a = 10
b = 20
list = [1, 2, 3, 4, 5 ];
if ( a in list ):
print ("Line 1 - a is available in the given list")
else:
print ("Line 1 - a is not available in the given list")
if ( b not in list ):
print ("Line 2 - b is not available in the given list")
else:
print ("Line 2 - b is available in the given list")
a=2
if ( a in list ):
print( "Line 3 - a is available in the given list")
else:
print ("Line 3 - a is not available in the given list")
Output:
Line 1 - a is not available in the given list
Line 2 - b is not available in the given list
Line 3 - a is available in the given list
ADP MANUAL
b. Read your name and age and write a program to display the year in which you will turn 100 years old
Output
What is your name: Dev
How old are you: 3
Dev will be 100 years old in the year 2119
ADP MANUAL
c. Read radius and height of a cone and write a program to find the volume of a cone.
Program:
height=38
radius=35
pie=3.14285714286
volume=pie*(radius*radius)*height/3
print("volume of the cone="+str(volume))
Output:
volume of the cone= 48766.666666711004
ADP MANUAL
d. Write a program to compute distance between two points taking input from the user (Hint: use
Pythagorean theorem)
Program:
x1=int(input("enter x1 : "))
x2=int(input("enter x2 : "))
y1=int(input("enter y1 : "))
y2=int(input("enter y2 : "))
result= ((((x2 - x1 )**2) + ((y2-y1)**2) )**0.5)
print("distance between",(x1,x2),"and",(y1,y2),"is : ",result)
Output
enter x1 : 8
enter x2 : 6
enter y1 : 9
enter y1 : 5
distance between (8,6) and (9,5) is : 4.47213595
ADP MANUAL
def countCharacterType(str):
vowels = 0
consonant = 0
specialChar = 0
digit = 0
for i in range(0, len(str)):
ch = str[i]
if ( (ch >= 'a' and ch <= 'z') or
(ch >= 'A' and ch <= 'Z') ):
# To handle upper case letters
ch = ch.lower()
if (ch == 'a' or ch == 'e' or ch == 'i'
or ch == 'o' or ch == 'u'):
vowels += 1
else:
consonant += 1
elif (ch >= '0' and ch <= '9'):
digit += 1
else:
specialChar += 1
print("Vowels:", vowels)
print("Consonant:", consonant)
print("Digit:", digit)
print("Special Character:", specialChar)
# Driver function.
str = "geeks for geeks121"
countCharacterType(str)
Output:
Vowels: 5
Consonant: 8
Digit: 3
Special Character: 2
ADP MANUAL
B) write a program to create and display dictionary by storing the antonyms of words. find the antonym
of a particular word given by the user from the dictionary using while loop in python
Program
print('enter word from following words ')
no ={'right':'left','up':'down','good':'bad','cool':'hot','east':'west'}
for i in no.keys():
print(i)
y = input()
if y in no :
print('antonym is ', no[y])
else:
print('not in the list given no ')
Output:
enter word from following words
right
up
good
cool
east
ADP MANUAL
C)Write a Program to find the sum of a Series 1/1! + 2/2! + 3/3! + 4/4! +…….+ n/n!. (Input :n = 5,
Output : 2.70833)
Program
# Python code to find smallest K-digit
# number divisible by X
def sumofSeries(num):
# Computing MAX
res = 0
fact = 1
return res
n=5
print("Sum: ", sumofSeries(n))
Output:
Sum: 2.70833
ADP MANUAL
D)In number theory, an abundant number or excessive number is a number for which the sum of its
proper divisors is greater than the number itself. Write a program to find out, if the given number is
abundant. (Input: 12, Sum of divisors of 12 = 1 + 2 + 3 + 4 + 6 = 16, sum of divisors 16 > original number
12)
Output:
YES
NO
ADP MANUAL
3: PROGRAMS ON LIST
a). Read a list of numbers and print the numbers divisible by x but not by y (Assume x = 4 and y = 5).
def result(N):
# iterate from 0 to N
for num in range(N):
# Short-circuit operator is used
if num % 4 == 0 and num % 5 != 0:
print(str(num) + " ", end = "")
else:
pass
# Driver code
if __name__ == "__main__":
# input goes here
N = 100
# Calling function
result(N)
output:- 4 8 12 16 24 28 32 36 44 48 52 56 64 68 72 76 84 88 92 96
ADP MANUAL
B). Read a list of numbers and print the sum of odd integers and even integers from the list.(Ex: [23, 10,
15, 14, 63], odd numbers sum = 101, even numbers sum = 24)
# Python program to count Even
# and Odd numbers in a List
NumList = []
Even_Sum = 0
Odd_Sum = 0
j=0
NumList.append(value)
if(NumList[j] % 2 == 0):
else:
j = j+ 1
Output:
Please enter the total number of list elements: 5
Please enter the value of 1 element:23
Please enter the value of 2 element:10
Please enter the value of 3 element:15
Please enter the value of 4 element:14
Please enter the value of 5 element:63
Sum of Even Numbers in this List=24
Sum of odd Numbers in this List =101
ADP MANUAL
c. Read a list of numbers and print numbers present in odd index position. (Ex: [10, 25, 30, 47, 56, 84, 96],
The numbers in odd index position: 25 47 84).
Program:
# Python3 implementation to
# arrange odd and even numbers
arr = list()
print(end="Enter the List Size: ")
arrTot = int(input())
print(end="Enter " +str(arrTot)+ " Numbers: ")
for i in range(arrTot):
arr.append(int(input()))
print("\nNumbers at Odd Position: ")
for i in range(arrTot):
if i%2!=0:
print(end=str(arr[i]) +" ")
print()
Output:- Enter the List Size: 7
Enter the 7 number10
25
30
47
56
84
Numbers at the odd position 25 47 84
ADP MANUAL
d). Read a list of numbers and remove the duplicate numbers from it. (Ex: Enter a list with duplicate
elements: 10 20 40 10 50 30 20 10 80, The unique list is: [10, 20, 30, 40, 50, 80]
Program:
my_list = [10,20,40,10,50,30,20,10,80]
print("List Before ", my_list)
temp_list = []
for i in my_list:
if i not in temp_list:
temp_list.append(i)
my_list = temp_list
print("List After removing duplicates ", my_list)
Output:
List Before [10,20,40,10,50,30,20,10,80]
List After removing duplicates [10,20,40,50,30,80]
ADP MANUAL
PROGRAMS ON TUPLE
a. Given a list of tuples. Write a program to find tuples which have all elements divisible by K from a
list of tuples. test_list = [(6, 24, 12), (60, 12, 6), (12, 18, 21)], K = 6, Output : [(6, 24, 12), (60, 12, 6)]
Program:
test_list = [(6, 24, 12), (60, 12, 6), (12, 18, 21)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K=6
# all() used to filter elements
res = [sub for sub in test_list if all(ele % K == 0 for ele in sub)]
# printing result
print("K Multiple elements tuples : " + str(res))
Output
The original list is: = [(6, 24, 12), (60, 12, 6), (12, 18, 21)]
K Multiple elements tuples : [(6, 24, 12), (60, 12, 6)]
ADP MANUAL
B) b. Given a list of tuples. Write a program to filter all uppercase characters tuples from given list of
tuples. (Input: test_list = [(“GFG”, “IS”, “BEST”), (“GFg”, “AVERAGE”), (“GfG”, ), (“Gfg”, “CS”)],
Output : [(„GFG‟, „IS‟, „BEST‟)]).
Program
test_list = [("GFG", "IS", "BEST"), ("GFg", "AVERAGE"), ("Gfg", "CS")]
# printing original list
print("The original list is : " + str(test_list))
res_list = []
for sub in test_list:
res = True
for ele in sub:
# checking for uppercase
if not ele.isupper():
res = False
break
if res:
res_list.append(sub)
# printing results
print("Filtered Tuples : " + str(res_list))
Output
The original list is : [("GFG", "IS", "BEST"), ("GFg", "AVERAGE"), ("Gfg", "CS")]
Filtered Tuples : [("GFG", "IS", "BEST")]
ADP MANUAL
c. Given a tuple and a list as input, write a program to count the occurrences of all items of the list in the
tuple. (Input : tuple = ('a', 'a', 'c', 'b', 'd'), list = ['a', 'b'], Output : 3)
Program:
# Python3 Program to count occurrence
# of all elements of list in a tuple
from collections import Counter
def countOccurrence(tup, lst):
count = 0
for item in tup:
if item in lst:
count+= 1
return count
# Driver Code
tup = ('a', 'a', 'c', 'b', 'd')
lst = ['a', 'b']
print(countOccurrence(tup, lst))
Output: 3
ADP MANUAL
PROGRAMS ON SET
a) Write a program to generate and print a dictionary that contains a number (between 1 and n) in the
form (x, x*x)
Program:
n=int(input("Input a number "))
d = dict()
for x in range(1,n+1):
d[x]=x*x
print(d)
Output:
Input a number 4
{1: 1, 2: 4, 3: 9, 4: 16}
ADP MANUAL
B ) Write a program to perform union, intersection and difference using Set A and Set B
Program:
A = {0, 2, 4, 6, 8};
B = {1, 2, 3, 4, 5};
# union
print("Union :", A | B)
# intersection
print("Intersection :", A & B)
# difference
print("Difference :", A - B)
# symmetric difference
print("symmetric difference: ",A ^B)
Output:
Union : {0,1,2,3,4,5,6,8}
Intersection : {2,4}
Difference : {0, 8, 6}
symmetric difference : {0,1,3,5,6,8}
ADP MANUAL
C).Write a program to count number of vowels using sets in given string (Input : “Hello World”, Output:
No. of vowels : 3)
Program:
def vowel_count(str):
# Initializing count variable to 0
count = 0
# Creating a set of vowels
vowel = set("aeiouAEIOU")
# Loop to traverse the alphabet
# in the given string
for alphabet in str:
# If alphabet is present
# in set vowel
if alphabet in vowel:
count = count + 1
print("No. of vowels :", count) # Driver code
str = "Hello World"
vowel_count(str)
Output:
No. of vowels : 3
ADP MANUAL
D).Write a program to form concatenated string by taking uncommon characters from two strings using
set concept (Input : S1 = "aacdb", S2 = "gafd", Output : "cbgf").
Program:
def concatenetedString(s1, s2):
res = "" # result
m = {}
return res
# Driver Code
if __name__ == "__main__":
s1 = " aacdb "
s2 = " gafd "
print(concatenetedString(s1, s2))
Output: cbgf
ADP MANUAL
PROGRAMS ON DICTONARY
a. Write a program to do the following operations:
i. Create a empty dictionary with dict() method
Program:
# Python3 code to demonstrate use of
# {} symbol to initialize dictionary
emptyDict = {}
# print dictionary
print(emptyDict)
# print length of dictionary
print("Length:", len(emptyDict))
# print type
print(type(emptyDict))
output :-
Length: 0
<type 'dict'>
output:-
The dictionary before deletion : {'Nikhil': 7, 'Akshat': 1, 'Akash': 2}
Value associated to poppped key is : 2
Dictionary after deletion is : {'Nikhil': 7, 'Akshat': 1}
output:-
{'model': 'Mustang', 'year': 1964}
ii. clear() method
Program:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.clear()
print(car)
output:-
{}
ADP MANUAL
c. Given a dictionary, write a program to find the sum of all items in the dictionary.
Program:
def returnSum(myDict):
list = []
for i in myDict:
list.append(myDict[i])
final = sum(list)
return final
dict = {'a': 100, 'b':200, 'c':300}
print("Sum :", returnSum(dict))
output:-
('Sum :', 600)
A). Given a string, write a program to check if the string is symmetrical and palindrome or not. A string is said to be symmetrical if both the
halves of the string are the same and a string is said to be a palindrome string if one half of the string is the reverse of the other half or if a
string appears same when read forward or backward.
def palindrome(a):
mid = (len(a)-1)//2
start = 0
last = len(a)-1
flag = 0
if (a[start]== a[last])
start += 1
last -= 1
else:
flag = 1
break
if flag == 0:
def symmetry(a):
n = len(a)
flag = 0
if n%2:
mid = n//2 +1
else:
mid = n//2
start1 = 0
start2 = mid
if (a[start1]== a[start2]):
start1 = start1 + 1
start2 = start2 + 1
else:
flag = 1
break
if flag == 0:
else:
string = 'amaama'
palindrome(string)
ADP MANUAL
symmetry(string)
b.write a program to read a string and count the number of vowel letters and print all letters except ‘e’
and ‘s’.
Program:
def Check_Vow(string, vowels):
final = [each for each in string if each in vowels]
print(len(final))
print(final)
# Driver Code
string = "I love you devanshi"
vowels = "AaIiOoUu"
Check_Vow(string, vowels);
output:- 6 ['i', 'o', 'o', 'u', 'a',’i’]
c. Write a program to read a line of text and remove the initial word from given text. (Hint: Use split()
ADP MANUAL
Program:
test_str = "Gandham"
all_freq = {}
for i in test_str:
if i in all_freq:
all_freq[i] += 1
else:
all_freq[i] = 1
# printing result
print ("Count of all characters in GeeksforGeeks is :\n "+ str(all_freq))
Output
Count of all characters in Gandham is :
{‘G’: 1, ‘a’:2 , ‘n’: 1, ‘d’: 1, ‘h’: 1, ‘m’:1}
a. A generator is a function that produces a sequence of results instead of a single value. Write a
generator function for Fibonacci numbers up to n.
def fib(num):
a=0
b=1
for i in range(num):
yield a
a, b = b, a + b # Adds values together then swaps them
for x in fib(10):
print(x)
Output:
0
1
1
2
3
5
8
13
21
34
output:-
None
{'d': 6, 'c': 4, 'a': 10, 'b': 8}
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
n=int(input("Input a number to compute the factiorial : "))
print(factorial(n))
output:-
Input a number to compute the factiorial : 4
24
d. Given a list of n elements, write a linear_search() function to search a given element x in a list.
ADP MANUAL
Program:
def search(arr, n, x):
output:-
Element is present at index 3
BUILT IN FUNCTIONS
ADP MANUAL
a).Write a program to demonstrate the working of built-in statistical functions mean(), mode(),
median() by importing statistics library.
Program:
import statistics
li = [1, 3, 3, 2, 2, 1]
# using mean() to calculate average of list elements
print ("The average of list values is : ",end="")
print (statistics.mean(li))
# using mode() to print maximum occurring of list elements
print ("The maximum occurring element is : ",end="")
print (statistics.mode(li))
# using median() to print decimal occurring of list elements
print ("The maximum occurring element is : ",end="")
print (statistics.median(li))
Output
The average of list values is : 2
The maximum occurring element is : 1
The maximum occurring element is : 2.0
b.Write a program to demonstrate the working of built-in trignometric functions sin(), cos(), tan(),
hypot(), degrees(), radians() by importing math module.
Program:
import math
print(math.sin(math.pi/3)) #pi/3 radians is converted to 60 degrees
print(math.tan(math.pi/3))
print(math.cos(math.pi/6))
print(math.degrees((math.pi/2)))
print(math.radians(60))
print(math.hypot(3))
OUTPUT:-
0.8660254037844386
1.7320508075688767
0.8660254037844387
90.0
1.0471975511965976
3.0
ADP MANUAL
C) Write a program to demonstrate the working of built-in Logarithmic and Power functions exp(),
log(), log2(), log10(), pow() by importing math module
Program:
# Python code to demonstrate the working of
# log(a,Base)
import math
# Printing the log base e of 14
print ("Natural logarithm of 14 is : ", end="")
print (math.log(14))
# Printing the log base 5 of 14
print ("Logarithm base 5 of 14 is : ", end="")
print (math.log(14,5))
output:- Natural logarithm of 14 is : 0.0
Logarithm base 5 of 14 is : 0.6931471805599453
the exponatial of the 12 is : 162754.79141900392
D.Write a program to demonstrate the working of built-in numeric functions ceil(), floor(), fabs(),
ADP MANUAL
import math
a = 2.3
# returning the ceil of 2.3
print ("The ceil of 2.3 is : ", end="")
print (math.ceil(a))
# returning the floor of 2.3
print ("The floor of 2.3 is : ", end="")
print (math.floor(a))
a = -10
b= 5
# returning the absolute value.
print ("The absolute value of -10 is : ", end="")
print (math.fabs(a))
# returning the factorial of 5
print ("The factorial of 5 is : ", end="")
print (math.factorial(b))
a = -10
b = 5.5
c = 15
d=5
# returning the copysigned value.
print ("The copysigned value of -10 and 5.5 is : ", end="")
print (math.copysign(5.5, -10))
# returning the gcd of 15 and 5
print ("The gcd of 5 and 15 is : ", end="")
print (math.gcd(5,15))
OUTPUT:-
The ceil of 2.3 is : 3
The floor of 2.3 is : 2
The absolute value of -10 is : 10.0
The factorial of 5 is : 120
The copysigned value of -10 and 5.5 is : -5.5
The gcd of 5 and 15 is : 5
ADP MANUAL
else:
print("timed out!")
elif choice==3:
print("balance left in your account")
time.sleep(2.0)
print("40000 /-")
elif choice==4:
old=int(input("enter old pin number :"))
new=int(input("enter new pin number :"))
time.sleep(2.0)
print("pin number changed")
print("thank you for your service")
Output
****************************************
enter your pin code:3823
welcome to Dev bank
1.withdraw
2.transfer money
3.balance enquiry.
4.pin change
****************************************
enter your choice here:1
1.savings
2.current
enter your choice:1
enter the cash below:10000
wait!
balance left : 30000
****************************************
****************************************
enter your choice here:3
balance left in your account
40000 /-
****************************************
enter your pin code:3823
ADP MANUAL
C) Create a SavingsAccount class that behaves just like a BankAccount, but also has an interest rate and
a method that increases the balance by the appropriate amount of interest (Hint:use Inheritance).
Program:
from datetime import datetime
class Account:
total_accounts = 0
interest_rate = 0.04
def __init__(self, act_no, act_balance, type):
self.act_no = act_no
self.act_balance = act_balance
self.type = type
self.created_date= datetime.now()
Account.total_accounts += 1
def returns(self, year):
return f'Your balance is worth {self.act_balance * 1.04} in {year} year(s)'
class MultiCurrencyAccount(Account):
interest_rate = 0.01
def __init__(self, act_no, act_balance, type, currencies):
self.currencies=currencies
super().__init__(act_no,act_balance,type)
myaccount=Account(5555555005,100,"savings")
print(myaccount.returns(1))
print(myaccount.returns(2))
Output
Your balance is worth 104.0 in 1 year(s)
Your balance is worth 104.0 in 2 year(s)
ADP MANUAL
C). Write a program to create an employee class and store the employee name, id, age, and salary using
the constructor. Display the employee details by invoking employee_info() method and also using
dictionary (__dict__).
Program:
class Employee:
__id=0
__name=""
__gender=""
__city=""
__salary=0
d. Access modifiers in Python are used to modify the default scope of variables. Write a program to
demonstrate the 3 types of access modifiers: public, private and protected.
Program:
class Super:
# public data member
var1 = None
# protected data member
_var2 = None
a. . Write a program to read a filename from the user, open the file (say firstFile.txt) and then perform
the following operations:
i. Count the sentences in the file.
Program:
# Opening a file
file = open("mytext.txt","r")
Counter = 0
# Reading from file
Content = file.read()
CoList = Content.split("\n")
for i in CoList:
if i:
Counter += 1
print("This is the number of lines in the file")
print(Counter)
Output
This is the number of lines in the file
3
ii. Count the words in the file.
Program:
def display_words():
file = open("mytext.txt","r")
data = file.read()
words = data.split()
print("number of words in file:",len(words))
file.close()
display_words()
Output
number of words in file: 14
Program:
file = open("mytext.txt", "r")
#read the content of file
data = file.read()
#get the length of the data
number_of_characters = len(data)
print('Number of characters in text file :', number_of_characters)
Output
Number of characters in text file : 87
b. . Create a new file (Hello.txt) and copy the text to other file called target.txt. The target.txt file
should store only lower case alphabets and display the number of lines copied
Program:
with open('mytext.txt','r') as firstfile, open('second.txt','a') as secondfile:
If you run this automatically create the 2nd new file name with second,txt
In that file automatically generate the information from mytext.txt
C). c. Write a Python program to store N student‟s records containing name, roll number and branch. Print
the given branch student‟s details only.
ADP MANUAL
Program:
class Student:
marks = []
def getData(self, rn, name, m1, m2, m3):
Student.rn = rn
Student.name = name
Student.marks.append(m1)
Student.marks.append(m2)
Student.marks.append(m3)
def displayData(self):
print ("Roll Number is: ", Student.rn)
print ("Name is: ", Student.name)
print ("Marks are: ", Student.marks)
print ("Total Marks are: ", self.total())
print ("Average Marks are: ", self.average())
def total(self):
return (Student.marks[0] + Student.marks[1] +Student.marks[2])
def average(self):
return ((Student.marks[0] + Student.marks[1] +Student.marks[2])/3)
s1 = Student()
s1.getData(r, name, m1, m2, m3)
s1.displayData()
Output
Enter the roll number: 528
Enter the name: kiran
Enter the marks in the first subject: 59
Enter the marks in the second subject: 69
Enter the marks in the third subject: 78
Roll Number is: 528
Name is: kiran
Marks are: [59, 69, 78]
Total Marks are: 206
Average Marks are: 68.66666666666667
DBMS Commands
1. Implement Data Definition Language(DDL) Statements: (Create table, Alter table, Drop table) 2.
1.Implement Data Manipulation Language(DML) Statements
ADP MANUAL
DDL
o CREATE
o ALTER
o DROP
o TRUNCATE
CREATE:
ALTER:
ALTER TABLE Student ADD Number int;
ALTER TABLE Student Drop column Number;
ALTER TABLE Student Alter Number BIgint;
DROP
Truncate
Truncate table Student
DML
o INSERT
o UPDATE
o DELETE
o SELECT
INSERT
UPDATE
o DELETE
SELECT