0% found this document useful (0 votes)
5 views16 pages

Computer Practical JournalHY

The document contains a series of Python function implementations for various tasks, including creating lists based on digit sums, performing left and right shifts on lists, filtering employee records from a dictionary, and manipulating text and CSV files. Each function is accompanied by example usage and input/output descriptions. The tasks range from basic list operations to file handling and data processing in CSV format.

Uploaded by

abhirupmitra556
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views16 pages

Computer Practical JournalHY

The document contains a series of Python function implementations for various tasks, including creating lists based on digit sums, performing left and right shifts on lists, filtering employee records from a dictionary, and manipulating text and CSV files. Each function is accompanied by example usage and input/output descriptions. The tasks range from basic list operations to file handling and data processing in CSV format.

Uploaded by

abhirupmitra556
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

1) Write a function CreateList(val) in python which will take a list of

numbers named val and will create another list sum by adding
numbers from val where sum of digits of the numbers is more than
50. The function will return the new list sum. Print the list in the
reverse order.

def CreateList(val):
sum_list = []
for num in val:
num_str = str(num).replace('-', '')
digit_sum = sum(int(digit) for digit in num_str)
if digit_sum > 50:
sum_list.append(num)
return sum_list
val = [999999999, -123456789, 888888888, -987654321,
555555555]
new_list = CreateList(val)
print(“Output:”)
print(new_list[::-1])
2) Write a function LeftShift(L) in Python which will take a list of
numbers L as the parameter and will perform left shift of numbers
and thus modifies the original list L. The function will return the
modified list. Print the modified list.

def LeftShift(L):
n=len(L)
a=L[0]
for i in range(1,n,1):
L[i-1]=L[i]
L[-1]=a
return L
L=[2,3,4,7,5]
LeftShift(L)
print(“Output:”)
print("Modified List: ",L)

3) Write a function RShift(ARR,N) in python which will take a list of


numbers and a single value within list ARR and variable N
respectively. The function will perform right shift on list ARR for N
number of times and thus modify the list. Print the modify list.

def RShift(ARR, N):


print("The original list: ", ARR)
for i in range(N):
a = ARR[-1]
for j in range(len(ARR) - 2, -1, -1):
ARR[j + 1] = ARR[j]
ARR[0] = a
print("Output:")
print("The modified list: ", ARR)
L = []
n = int(input("Enter how many values to add: "))
for i in range(n):
a = int(input("Enter a value: "))
L.append(a)
b = int(input("How many times Right Shift: "))
RShift(L, b)

4) Write
a function ShowEmp(EMP,S,A) in Python which will take a
dictionary EMP, salary S and location A as parameter. The
Function will print employee records whom come from location A
and earns more than salary mentioned in S consider that the
dictionary contains Employee name as key and dept, salary,
location in form of list as value.

def ShowEmp(EMP,S,A):

print("Showing employee details who earns more

then: ",S,"andcome from: ",A)

for k,v in EMP.items():


if v[1]>S and v[2]==A:
print(k,v)
emp={"Jamuna":["HR",43000,"GOA"],"Ramesh":
["PRD",27000,"PUNE"],"Nihit":["R&D",57000,"DELHI"]}
print("Give required data to show employee details: ")
a=int(input("Enter Salary: "))
b=input("Enter location: ")
ShowEmp(emp,a,b)

5) Write a function Library(file,isbn) in python which takes variable file


containing text file books.txt and book id number in variable isbn
as parameters. The function will print a list of lines starting with
isbn number. The function will print how many such lines are
counted.

def Library(file,isbn):
with open (file,"r") as f:
L=f.readlines()
c=0
for line in L:
wl=line.split()
if wl[0]==isbn:
print(line)
c=c+1
print("Number of such lines: ",c)
f.close()
Library("books.txt","14350079")

Example:
14350079 Python_Programming John_Smith 2020
12345678 Data_Science Mary_Johnson 2019
14350079 Machine_Learning Alex_Wilson 2021
98765432 Artificial_Intelligence Sarah_Lee 2022
14350079 Deep_Learning Michael_Brown 2023

6) Write a function Inventory(myfile,w) in python to print all the lines


from the text file stock.txt which are having the particular word
mentioned in w. Print the number of lines having that word.

def Inventory(myfile, w):


f = open(myfile, "r")
l = f.readlines()
c=0
for line in l:
if w in line:
print(line, end="")
c += 1
print("number of such lines:", c)
f.close()
Inventory("stock.txt", "python")

Example:
python is great
java is popular
I love python
python 3.10 is awesome
c++ is fast
7)

Write a function AddShow() in python which will add multiple times into text
file story.txt. If the contain at least five words. Find even position lines from
the text file story.txt.

def AddShow():
f = open("story.txt", "a")
n = int(input("Enter how many lines: "))
for i in range(n):
s = input("Enter a line: ")
wl = s.split()
if len(wl) >= 5:
f.write(s + "\n")
f.close()
f = open("story.txt", "r")
lines = f.readlines()
for i in range(1, len(lines), 2):
print(lines[i], end="")
f.close()
AddShow()

Example Usage:
Enter how many lines: 4
Enter a line: This is a short line
Enter a line: Python is a very powerful and easy programming
language
Enter a line: Today is Friday and it is raining heavily outside
Enter a line: Hello world

8)
Write a function ModifyText(myfile) in python which will take a text file as
parameter delete all the lines from the lines from the text file story.txt which
ends with the word (“java, not case sensitive). The function will display all
the remaining lines from the text file.

def ModifyText(myfile):
f = open(myfile, "r")
lines = f.readlines()
f.close()
remaining_lines = []
for line in lines:
stripped_line = line.strip()
if not stripped_line.lower().endswith("java"):
remaining_lines.append(line)
f = open(myfile, "w")
for line in remaining_lines:
f.write(line)
f.close()
print("Remaining lines in file:")
for line in remaining_lines:
print(line, end="")

Input File:
Python is a powerful language
I love programming in Java
Machine learning is amazing
C++ is widely used
Backend is written in java
AI will shape the future
9)

Write a function CopyText(myfile1, myfile2) which takes two text file names
in myfile1 and myfile2 respectively as parameter. Copy all the lines from
myfile1 to myfile2 which is starting word “The”. Print all lines from text file
myfile2.

def CopyText(myfile1, myfile2):


f1 = open(myfile1, "r")
lines = f1.readlines()
f1.close()
selected_lines = []
for line in lines:
if line.lstrip().startswith("The"):
selected_lines.append(line)
f2 = open(myfile2, "w")
for line in selected_lines:
f2.write(line)
f2.close()
print("Lines copied into", myfile2 + ":")
for line in selected_lines:
print(line, end="")
CopyText("file1.txt", "file2.txt")

Input File:
This is an example
The sun rises in the east
Python is easy
The moon shines at night
We are learning Python
The cat is sleeping

10)

Write a function Create csv() in python which will create a csv file
employee.csv and will create multiple records of employees into
employee.csv each employee record contains following information:
eid, ename, edept, eloc, esal, eage.
import csv
def Create_csv():
f = open("employee.csv", "w", newline='')
wobj = csv.writer(f)
n = int(input("Enter how many employee records: "))
for i in range(n):
a = input("Enter Employee ID: ")
b = input("Enter Employee Name: ")
c = input("Enter Department: ")
d = input("Enter Location: ")
e = input("Enter Salary: ")
f = input("Enter Age: ")
r=[a,b,c,d,e,f]
L.append(r)
wobj.writerows(L)
wobj.close()
f.close()
Create_csv()

Sample Run:

Suppose the user enters 2 for the number of employees and provides:
101, Alice, HR, Delhi, 50000, 28
102, Bob, IT, Mumbai, 60000, 32
11)

Write a function ShowEMP(mycsv1) which takes a csv file name mycsv1 as


permitted and will shoe employee records where location is “Bengaluru”
and employees work in “R and D” Department print how many such records
are there in csv file mycsv1. Consider each record of employee contains
following information:

EID, ENAME, ESAL, EDEPT, ELOC.

import csv
def ShowEMP(mycsv1):
count = 0
f = open(mycsv1, "r")
reader = csv.DictReader(f)
for row in reader:
if row['ELOC'] == 'Bengaluru' and row['EDEPT'] == 'R and D':
print(row)
count += 1
f.close()
print("Total records where location is 'Bengaluru' and
department is 'R and D':", count)

Input File:

EID,ENAME,ESAL,EDEPT,ELOC
101,John Doe,50000,R and D,Bengaluru
102,Jane Smith,60000,Marketing,Mumbai
103,Bob Johnson,55000,R and D,Bengaluru
104,Alice Williams,70000,R and D,Chennai
105,Michael Brown,52000,R and D,Bengaluru

12)
12)
Write a function ShowREC() Two show records of customers who has
purchased more than 3500 and who have purchased products
manufactured by "SAMSUNG" from csv file cust.csv. Print total price
and average price of purchase done by these customers.

import csv
def ShowREC():
filename = 'cust.csv'
total_price = 0
count = 0
try:
f = open(filename, "r")
reader = csv.DictReader(f)
for row in reader:
try:
price = float(row['Price'])
manufacturer = row['Manufacturer']
if price > 3500 and manufacturer == 'SAMSUNG':
print(row)
total_price += price
count += 1
except ValueError:
print(f"Skipping record with invalid price: {row['Price']}")
f.close()
if count > 0:
average_price = total_price / count
print(f"Total price of purchases: {total_price}")
print(f"Average price of purchases: {average_price}")
else:
print("No records found matching criteria.")
except FileNotFoundError:
print("File not found.")
except KeyError:
print("CSV file missing required columns.")
Input File:

CustomerID,Product,Price,Manufacturer
1,Smartphone,4000,SAMSUNG
2,Tablet,3000,Apple
3,TV,5000,SAMSUNG
4,Laptop,4500,SAMSUNG
5,Headphones,2500,SAMSUNG
13)
Write a function CopyRec(office1, office2) in python which will take two csv files
in office1 and office2 as parameters and will copy records of products where price
is more than 3000 and the product is purchased from “Goa” from office1 to
office2. Print all records from csv file office2. Consider each record of csv file
contains following information-
PID, PNAME, PPRICE, PMANF, PLOC.

import csv

def CopyRec(office1, office2):


with open(office1, 'r') as f1, open(office2, 'w', newline='') as f2:
reader = csv.DictReader(f1)
writer = csv.DictWriter(f2, fieldnames=reader.fieldnames)
writer.writeheader()
records = [row for row in reader if float(row['PPRICE']) > 3000 and
row['PLOC'] == 'Goa']
writer.writerows(records)
with open(office2, 'r') as f3:
for row in csv.DictReader(f3):
print(row)

Input File:

PID,PNAME,PPRICE,PMANF,PLOC
101,Phone,3200,Sony,Goa
102,Laptop,2800,Dell,Mumbai
103,Camera,4500,GoPro,Goa
104,TV,5000,Samsung,Delhi
105,Speaker,3500,Bose,Kolkata
106,Tablet,4000,Apple,Goa

You might also like