<!-- CS PRACTIAL RECORD THING -->
<!--
@media print {
abbr{
clear: both;
page-break-after: always;
}
}
-->
#### Program 1:
<font size="5px">
Write a program to generate all perfect numbers between a given range. \[A number is said to be perfect if the sum of divisors is equal to the number. Example 6: Divisors are 1,2,3 and the sum is 1 + 2 + 3 = 6]
```python
r = range(*eval(input("Input a range (start, stop): "))) #input range
for i in r:
s = 0
for j in range(1, i):
if(i % j == 0):
s += j
if s == i:
print(f"{s} is a perfect number")
```
</font>
##### output:
```
Input a range (start, stop): 1, 500
6 is a perfect number
28 is a perfect number
496 is a perfect number
```
#### Program 2:
Write a python program to generate the Armstrong number between a given range. \[A number is said to be Armstrong numbers iff the sum of cube of the digits is equal to the number. Example: 153 =>13 + 53 + 33= 153]
```python
r = range(*eval(input("Input a range (start, stop): "))) #input range
for i in r:
a = (i%10)**3 + (i%100//10) ** 3 + (i//100) ** 3
if a == i:
print(i, "is an amstrong number")
```
##### output:
```
Input a range (start, stop): 100, 1000
153 is an amstrong number
370 is an amstrong number
371 is an amstrong number
407 is an amstrong number
```
#### Program 3:
Write a program to generate the given pattern.
```
1
2 6
3 7 10
4 8 11 13
5 9 12 14 15
```
```python
n = 5
for i in range(1,n+1):
print(i, end = " ")
for j in range(n-1,n-i,-1):
i += j
print(i, end = " ")
print()
```
##### output:
```
1
2 6
3 7 10
4 8 11 13
5 9 12 14 15
```
#### Program 4:
Write an interactive menu driven program to implement linear and binary search for a list of strings using functions.
```python
def lin_search(iter, t):
for i, e in enumerate(iter):
if t == e:
return e, i
raise RuntimeError("Item not found.")
def bin_search(iter, t, start=0, stop=-1):
if stop == -1: stop = len(iter)
mid = (start + stop)//2
if start == stop:
raise RuntimeError("Item not found.")
if iter[mid] == t:
return t, mid
elif iter[mid] < t:
return bin_search(iter, t, start=mid, stop=stop)
elif iter[mid] > t:
return bin_search(iter, t, start=start, stop=mid)
l = eval(input("Enter a list:")).sort()
t = eval(input("Enter the target:))
choice = int(input("""
1. Linear Search
2. Binary Search
> """))
choice = [lin_search, bin_search][choice-1]
res = choice(l, t)
print("found {} at position {}".format(*res))
```
##### output:
```
Enter a list: [1, 2, 3, 4, 5, 6, 7]
Enter the target: 4
1. Linear Search
2. Binary Search
> 2
found 4 at position 3
```
#### Program 5:
Write a Python program using function to sort the details of Doctors in descending order of their specialization using bubble sort. The Doctors detail includes DoctorId, Name and specialization which is stored as a nested list.
```python
#order of specialisations
spec = [
"Ophthalmologist",
"Pathologist",
"Pediatritian",
"Psychiatirst"
]
doctors = [
[100, "Raghav", "Pediatritian"],
[101, "Gopal", "Ophthalmologist"],
[102, "Pranav", "Psychiatirst"]
]
def bubbleSort(iter):
n = len(iter)
for i in range(n-1):
for j in range(0, n-i-1):
if spec.index(iter[j][-1]) > spec.index(iter[j + 1][-1]) :
iter[j], iter[j + 1] = iter[j + 1], iter[j]
return iter
for i in bubblesort(doctors):
print(*i)
```
##### output:
```
101 Gopal Ophthalmologist
100 Raghav Pediatritian
102 Pranav Psychiatirst
```
#### Program 6:
Write a Python program which has the function to sort the details of the Products in ascending order of their price using insertion sort. The nested list contains the details of the Product such as Pid, Pname, Qty and price.
```python
products = [
#Pid, Pname, Qty, Price
[226, "ice cream" , 2 , 40],
[100, "Potato Chips" , 1 , 20],
[127, "Gatorade" , 1 , 30]
]
def insertionSort(iter):
for i in range(0, len(iter)):
for j in range(i, len(iter)):
if iter[j][-1] < iter[i][-1]:
iter.insert(i, iter.pop(j))
return iter
for i in insertionSort(products):
print(*i)
```
##### output:
```
100 Potato Chips 1 20
127 Gatorade 1 30
226 ice cream 2 40
```
#### Program 7:
Write a Python program using functions to create a text file “Story.txt”, read lines from the text file “Story.txt” and display those words whose length is less than 4 characters.
file (`Story.txt`):
```
Python is an interpreted high-level general-purpose programming language.
ts design philosophy emphasizes code readability with its use of significant indentation.
ts language constructs as well as its object-oriented approach aim to help programmers write clear, logical code for small and large-scale projects.
Python is dynamically-typed and garbage-collected.
It supports multiple programming paradigms, including structured (particularly, procedural), object-oriented and functional programming.
It is often described as a "batteries included" language due to its comprehensive standard library.
```
```python
with open("Story.txt", "r") as f:
for i in f.readlines():
for j in i.split():
if len(j) <= 4:
print(j)
```
##### output:
```
is
an
ts
its
use
of
ts
as
as
its
aim
to
for
and
is
and
It
and
It
is
as
a
due
to
its
```
#### Program 8:
Write a Python program using function to count the number of words starting with the vowel in a file Books.txt
file (`Book.txt`):
```
Python is an interpreted high-level general-purpose programming language.
ts design philosophy emphasizes code readability with its use of significant indentation.
ts language constructs as well as its object-oriented approach aim to help programmers write clear, logical code for small and large-scale projects.
Python is dynamically-typed and garbage-collected.
It supports multiple programming paradigms, including structured (particularly, procedural), object-oriented and functional programming.
It is often described as a "batteries included" language due to its comprehensive standard library.
```
```python
count = 0
with open("Book.txt", "r") as f:
for i in f.readlines():
for j in i.split():
if j[0].lower() in 'aeiou':
count += 1
print(count,"words start with a vowel")
```
##### output:
```
28 words start with a vowel
```
#### Program 9:
Write a Python program which has the function to read from the file Exam.txt and display all the lines which ends with the word “health”.
file (`Exam.txt`)
```
Health care (also health-care or healthcare) is the maintenance or improvement of health via the prevention, diagnosis, treatment, recovery, or cure of disease, illness, injury, and other physical and mental impairments in people.
Health care is delivered by health professionals and allied health fields.
Medicine, dentistry, pharmacy, midwifery, nursing, optometry, audiology, psychology, occupational therapy, physical therapy, athletic training, and other health professions are all part of health care.
It includes work done in providing primary care, secondary care, and tertiary care, as well as in public health.
```
```python
with open('Exam.txt') as f:
for i in f.readlines():
if i.lower().endswith('health.'):
print(i)
```
##### output:
```
It includes work done in providing primary care, secondary care, and tertiary care, as well as in public health.
```
#### Program 10:
Write a python program to count and display words that stars with a vowel
```python
data = """
Arch Linux is an independently developed, x86-64 general-purpose GNU/Linux distribution that strives to provide the latest stable versions of most software by following a rolling-release model. The default installation is a minimal base system, configured by the user to only add what is purposely required.
"""
count = 0
for i in data.split():
if i[0].lower() in 'aeiou':
count += 1
print("words that stars with a vowel:", count)
```
##### output:
```
words that stars with a vowel: 13
```
#### Program 11:
Write an interactive menu driven Python program using binary file to perform the following tasks:
* Write the information of the car like CarNo,Carname, mileage and price onto the “CARS.DAT”
* Read from the file and display all the Toyota cars with their price.
```python
import pickle
data = [
#CarNo, Name, Milage, Price
[7561, 'Ford Endeavor', 14, 3381_000],
[2563, 'Toyota Innova', 12, 1718_000],
[1823, 'Tata Nexon', 22, 728_000],
[9273, 'Ford Ecosport', 22, 8190_000],
[5626, 'Toyota Fortuner', 10, 3073_000],
[8172, 'Hyundai i20', 19, 691_000],
[8273, 'Toyota Camry', 19, 4120_000],
[5178, 'Datsun Redi-GO', 22, 383_000],
[3726, 'Maruti Suzuki Swift', 24, 585_000]
]
with open('cars.dat', 'wb') as f:
pickle.dump(data, f)
with open('cars.dat', 'rb') as f:
for i in pickle.load(f):
if i[1].startswith("Toyota"):
print(*i)
```
##### output:
```
2563 Toyota Innova 12 1718000
5626 Toyota Fortuner 10 3073000
8273 Toyota Camry 19 4120000
```
#### Program 12:
Write a Python program to update the binary file “Mobile.dat” containing the information about mobile like ModelNo, memorycard, details and megapixel. The Modelno whose megapixel to be updated are accepted from the user.
```python
"""
the data in mobile.dat is stored as:
{
ModelNo(int) : [Name(str), Memory(int), Megapixel(int)]
...
}
"""
import pickle
def update( model, megapx ):
with open('mobile.dat', 'rb+') as f:
data = pickle.load(f)
data[model][2] = megapx
pickle.dump(data, f)
print("updated values:")
for i in data:
print(*i)
model = int(input("enter model number:"))
megapx = int(input("enter MegaPixels:"))
update(model, megapx)
```
##### output:
```
enter model number:100
enter MegaPixels:20
updated values:
100 IPhone 12 32 20
102 Samsung Galaxy 8 32 12
145 Nokia x50 12 4
```
#### Program 13:
Write a Python program to do the following:
* Write the information of the directory, like name, address, areacode and phone number on to the binary file Telephone.DAT
* Delete all the records of a specific areacode taken as input.
* Read from the file and display the details of all the records and also to count the number of records present in it.
```python
import pickle
data =[
#Name, pincode, phone
["joel", 690420, 9338859628],
["selva", 304324, 9678859452]
]
with open('telephone.dat', 'wb') as f:
pickle.dump(data, f)
a = int(input("enter pincode to delete records:"))
with open('telephone.dat', 'rb+') as f:
data = pickle.load(f)
for i in range(len(data)):
if data[i][1] == a:
data.pop(i)
with open('telephone.dat', 'wb+') as f:
pickle.dump(data, f)
with open('telephone.dat', 'rb') as f:
data = pickle.load(f)
print(len(data), "record(s)")
for i in data:
print(*i)
```
##### output:
```
enter pincode to delete records:304324
1 record(s)
joel 690420 9338859628
```
#### Program 14:
Write an interactive Python program to perform the writing operation on to the csv file “Student.csv”. The details to be written are Rno, Name, Marks in 5 subjects and Average. Read from the Student.csv file and display the details of those students whose Average is above the given range.
file (`student.csv`)
```
1,Arjun,69,48,28,68,98,62.2
2,Aasha,83,29,48,84,94,67.6
3,Karim,27,87,97,96,92,79.8
4,Sasha,98,76,47,73,84,75.6
5,Meera,97,83,27,32,12,50.2
```
```python
m = float(input("enter minimum average mark: "))
with open("student.csv") as f:
for i in f.readlines():
rec = i.strip().split(',')
if float(rec[-1]) > m:
print(*rec)
```
##### output:
```
enter minimum average mark: 69
3 Karim 27 87 97 96 92 79.8
4 Sasha 98 76 47 73 84 75.6
```
#### Program 15:
Write a Python program using functions to write the details of Employee on to the file emp.csv which has the following: Eno, Name, Designation, Department and Salary. Read from the file and display the Name and Salary of the employees who belong to a specific department.
file (`emp.csv`)
```
2738,Adams,Regional Manager,Administration,150000
8463,Sarah,Chief Executive Officer,Administration,500000
7353,Kumar,Intern,Research and Development,15000
5382,Anika,Intern,Finance,15000
4728,Rocky,Senior Manager,Research and Development,50000
3625,Drake,HR Manager,HR,45000
7236,Subha,Accountant,Finance,30000
8273,Prabu,Secretary,Administration,20000
```
```python
def insert():
rec = []
for i in ["ENo", "Name", "Designation", "Dept", "salary"]:
rec.append(
input("Enter " + i + ": ")
)
with open('emp.csv', 'a') as f:
f.write( ','.join(rec) + '\n' )
def display(des):
with open('emp.csv', 'r') as f:
for i in f.readlines():
rec = i.strip().split(',')
if rec[3] == des:
print(*rec)
try:
while True:
print("""
1 | Insert record
2 | Display records
^C | Exit
""")
x = input('>')
if x == '1':
insert()
elif x == '2':
display(
input("enter designation filter:")
)
except KeyboardInterrupt:
pass
```
##### output:
```
1 | Insert record
2 | Display records
^C | Exit
>1
Enter ENo: 13
Enter Name: Arjun
Enter Designation: Intern
Enter Dept: Research and Development
Enter salary: 69000
1 | Insert record
2 | Display records
^C | Exit
>2
enter designation filter: Research and Development
7353 Kumar Intern Research and Development 15000
4728 Rocky Senior Manager Research and Development 50000
13 Arjun Intern Research and Development 69000
^C
```
#### Program 16:
Write an interactive Python program to find the sum of boundary, non-boundary, left diagonal and right diagonal elements of a nested List A of size MxN.
```python
m = [
[1, 2, 3, 4],
[2, 3, 4, 5],
[3, 4, 5, 6],
[4, 5, 6, 7]
]
c = input(
"""
1 | Boundary sum
2 | Non Boundary sum
3 | Left Diagonal sum
4 | Right diagonal sum
^C | Exit
> """
)
print("matrix:\n")
for i in m:
print(*i)
print()
sum = 0
if c == '1':
for i, e in enumerate(m):
for j, e in enumerate(e):
if i == 0 or i == len(m)-1 \
or j == 0 or j == len(m[0])-1:
sum += e
elif c == '2':
for i, e in enumerate(m):
for j, e in enumerate(e):
if not( i == 0 or i == len(m)-1 \
or j == 0 or j == len(m[0])-1 ):
sum += e
elif c == '3':
for i, e in enumerate(m):
for j, e in enumerate(e):
if i == j:
sum += e
elif c == '4':
for i, e in enumerate(m):
for j, e in enumerate(e):
if i == len(m) - j:
sum += e
else:
print("invalid choice"); exit()
print("the",
["Boundary", "Non-Boundary",
"Left Diagonal", "Right Diagonal"][int(c)-1],
"sum is",
sum
)
```
##### output:
```
1 | Boundary sum
2 | Non Boundary sum
3 | Left Diagonal sum
4 | Right diagonal sum
^C | Exit
> 2
matrix:
1 2 3 4
2 3 4 5
3 4 5 6
4 5 6 7
the Non-Boundary sum is 16
```
#### Program 17:
Write an interactive Python program to do the following using functions:
* Accept a list of elements and exchange the first half with the second half of the list.
* Accept a list of strings and display the number of palindrome words present in it.
```python
c = input("""
a) Accept a list of elements and exchange the first half with the second half of the list.
b) Accept a list of strings and display the number of palindrome words present in it.
> """)
if c == 'a':
l = eval(input("input list:"))
n = len(l)
l[:n//2], l[n//2:] = l[n-n//2:], l[:n-n//2]
print(l)
elif c == 'b':
l = eval(input("input list:"))
count = 0
for i in l:
if i == i[::-1]:
count += 1
print("number of palindromes:", count)
```
##### output:
```
a) Accept a list of elements and exchange the first half with the second half of the list.
b) Accept a list of strings and display the number of palindrome words present in it.
> a
input list:[1, 2, 3, 4, 5, 6, 7]
[5, 6, 7, 1, 2, 3, 4]
```
```
a) Accept a list of elements and exchange the first half with the second half of the list.
b) Accept a list of strings and display the number of palindrome words present in it.
> b
input list:["hello", "wow", "racecar"]
number of palindromes: 2
```
#### Program 18:
Write an interactive Python program using the functions Push (Customer), Pop(Customer) and Show(Customer) to push, pop and display the Customer details like Customer ID, Name, Phone no from the Stack of Customers.
```python
#a customer instance is a [ID, Name, Phone]
stack = []
while True:
print( "1 | push customer\n"
"2 | pop customer\n"
"3 | show customers\n"
)
c = input("> ")
if c == '1':
rec = []
for i in ["ID", "Name", "Phone"]:
rec.append(
input(i+": ")
)
stack.append(rec)
print("inserted record")
if c == '2':
print("deleted record\n", *stack.pop())
if c == '3':
for i in stack:
print(*i)
```
##### output:
```
1 | push customer
2 | pop customer
3 | show customers
> 1
ID: 10
Name: bob
Phone: 9988977546
inserted record
1 | push customer
2 | pop customer
3 | show customers
> 3
10 bob 9988977546
1 | push customer
2 | pop customer
3 | show customers
> 2
deleted record
10 bob 9988977546
1 | push customer
2 | pop customer
3 | show customers
> ^C
```