0% found this document useful (0 votes)
9 views14 pages

Element Frequency and List Modifications

The document contains various Python programs and SQL queries for managing data, including functions for finding frequency in lists, modifying lists, reading and writing files, and performing operations on student and employee records. It also includes SQL commands for creating, updating, and querying tables related to LAB, SPORTS, BOOKS, and STUDENT. The document serves as a comprehensive guide for basic data manipulation using Python and SQL.

Uploaded by

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

Element Frequency and List Modifications

The document contains various Python programs and SQL queries for managing data, including functions for finding frequency in lists, modifying lists, reading and writing files, and performing operations on student and employee records. It also includes SQL commands for creating, updating, and querying tables related to LAB, SPORTS, BOOKS, and STUDENT. The document serves as a comprehensive guide for basic data manipulation using Python and SQL.

Uploaded by

deekshitha.c0211
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

# Program to find frequency of an element in a list

1
def frequency(lst, element):
count = 0
for item in lst:
if item == element:
count += 1
return count

# Main program
numbers = []
n = int(input("Enter number of elements: "))
for i in range(n):
val = int(input(f"Enter element {i+1}: "))
[Link](val)

element = int(input("Enter element to find frequency: "))


print(f"Frequency of {element} = {frequency(numbers, element)}")

2
# Function to modify list: even → ×2, odd → ÷3

def modify_list(lst):
new_list = []
for num in lst:
if num % 2 == 0:
new_list.append(num * 2)
else:
new_list.append(num / 3) # keep float result
return new_list

# Main program
nums = []
n = int(input("Enter total numbers: "))
for i in range(n):
[Link](int(input(f"Enter number {i+1}: ")))

result = modify_list(nums)
print("Modified List:", result)

#3
import random

# Generate a random number between 1 and 6


print("Rolling a die...")
die_value = [Link](1, 6)
print("You got:", die_value)

# Function to count IS, TO, UP in [Link]

def ISTOUPCOUNT():
count_is = 0
count_to = 0
count_up = 0

try:
f = open("[Link]", "r")
content = [Link]().upper().split()
[Link]()
for word in content:
if word == "IS":
count_is += 1
elif word == "TO":
count_to += 1
elif word == "UP":
count_up += 1

print("Count of IS =", count_is)


print("Count of TO =", count_to)
print("Count of UP =", count_up)

except FileNotFoundError:
print("File not found. Please create [Link] first.")

# Run function
ISTOUPCOUNT()

def analyze_file(filename):
vowels = "AEIOUaeiou"
count_vowel = count_consonant = count_upper = count_lower = 0

try:
with open(filename, "r") as f:
text = [Link]()
for ch in text:
if [Link]():
if ch in vowels:
count_vowel += 1
else:
count_consonant += 1
if [Link]():
count_upper += 1
if [Link]():
count_lower += 1

print("Vowels:", count_vowel)
print("Consonants:", count_consonant)
print("Uppercase:", count_upper)
print("Lowercase:", count_lower)

except FileNotFoundError:
print("File not found!")

# Call function
analyze_file("[Link]") # replace with actual file name

# Create file and then display words with #

filename = "[Link]"

# Writing line by line


with open(filename, "w") as f:
n = int(input("Enter number of lines: "))
for i in range(n):
line = input(f"Enter line {i+1}: ")
[Link](line + "\n")
# Reading and displaying with #
with open(filename, "r") as f:
for line in f:
words = [Link]().split()
print("#".join(words))

# Remove lines containing 'a' or 'A' and write to new file

with open("[Link]", "r") as fin, open("[Link]", "w") as fout:


for line in fin:
if 'a' not in line and 'A' not in line:
[Link](line)

print("Lines without 'a' copied to [Link]")

# Program to create, write and read [Link]

filename = "[Link]"

# Writing to file
with open(filename, "w") as f:
n = int(input("Enter number of lines to write: "))
for i in range(n):
line = input(f"Enter line {i+1}: ")
[Link](line + "\n")

# Reading from file


print("\nContents of [Link]:")
with open(filename, "r") as f:
print([Link]())

#10
filename = "[Link]"

try:
with open(filename, "r") as f:
text = [Link]().split()

vowels = "AEIOUaeiou"
count = 0
vowel_words = []

for word in text:


if word[0] in vowels:
count += 1
vowel_words.append(word)

print("Words starting with a vowel:", vowel_words)


print("Total count:", count)

except FileNotFoundError:
print("File not found! Please create [Link] first.")

filename = "[Link]"
try:
with open(filename, "r") as f:
print("Lines starting with 'The':")
for line in f:
if [Link]().startswith("The"):
print([Link]())

except FileNotFoundError:
print("File not found!")

#11
import pickle

filename = "[Link]"

# Write records
with open(filename, "wb") as f:
n = int(input("Enter number of students: "))
for i in range(n):
roll = int(input("Enter roll number: "))
name = input("Enter name: ")
record = [roll, name]
[Link](record, f)

# Search by roll number


search_roll = int(input("\nEnter roll number to search: "))
found = False

with open(filename, "rb") as f:


try:
while True:
rec = [Link](f)
if rec[0] == search_roll:
print("Student Found:", rec[1])
found = True
break
except EOFError:
pass

if not found:
print("Roll number not found!")

#12
import pickle
import os

filename = "[Link]"
tempfile = "[Link]"

# Write records
with open(filename, "wb") as f:
n = int(input("Enter number of students: "))
for i in range(n):
roll = int(input("Enter roll number: "))
name = input("Enter name: ")
marks = float(input("Enter marks: "))
record = [roll, name, marks]
[Link](record, f)
# Update marks
search_roll = int(input("\nEnter roll number to update marks: "))
updated = False

with open(filename, "rb") as fin, open(tempfile, "wb") as fout:


try:
while True:
rec = [Link](fin)
if rec[0] == search_roll:
print("Old Marks:", rec[2])
rec[2] = float(input("Enter new marks: "))
updated = True
[Link](rec, fout)
except EOFError:
pass

[Link](filename)
[Link](tempfile, filename)

if updated:
print("Marks updated successfully.")
else:
print("Roll number not found.")

#13
import csv

filename = "[Link]"

# Write CSV file


with open(filename, "w", newline="") as f:
writer = [Link](f)
n = int(input("Enter number of users: "))
for i in range(n):
uid = input("Enter User ID: ")
pwd = input("Enter Password: ")
[Link]([uid, pwd])

# Search for password


search_uid = input("\nEnter User ID to search: ")
found = False

with open(filename, "r") as f:


reader = [Link](f)
for row in reader:
if row[0] == search_uid:
print("Password for", search_uid, "is:", row[1])
found = True
break

if not found:
print("User ID not found.")

#14
import csv
import os
filename = "[Link]"
tempfile = "[Link]"

# Write CSV file


with open(filename, "w", newline="") as f:
writer = [Link](f)
n = int(input("Enter number of employees: "))
for i in range(n):
empid = input("Enter Employee ID: ")
name = input("Enter Name: ")
mobile = input("Enter Mobile No: ")
[Link]([empid, name, mobile])

# Update mobile
search_id = input("\nEnter Employee ID to update mobile no.: ")
updated = False

with open(filename, "r") as fin, open(tempfile, "w", newline="") as fout:


reader = [Link](fin)
writer = [Link](fout)
for row in reader:
if row[0] == search_id:
print("Old Mobile:", row[2])
row[2] = input("Enter new Mobile No: ")
updated = True
[Link](row)

[Link](filename)
[Link](tempfile, filename)

if updated:
print("Mobile number updated successfully.")
else:
print("Employee ID not found.")

#15
# Menu driven stack program using list

stack = []

def push():
item = input("Enter book detail to PUSH: ")
[Link](item)
print("Book pushed successfully.")

def pop():
if stack:
print("Popped book:", [Link]())
else:
print("Stack is empty.")

def peek():
if stack:
print("Top of stack:", stack[-1])
else:
print("Stack is empty.")

def search():
item = input("Enter book detail to SEARCH: ")
if item in stack:
print("Book found at position", [Link](item))
else:
print("Book not found.")

def display():
if stack:
print("Stack contents:", stack)
else:
print("Stack is empty.")

# Menu
while True:
print("\n--- Book Stack Menu ---")
print("1. PUSH\n2. POP\n3. PEEK\n4. SEARCH\n5. DISPLAY\n6. EXIT")
choice = int(input("Enter your choice: "))

if choice == 1:
push()
elif choice == 2:
pop()
elif choice == 3:
peek()
elif choice == 4:
search()
elif choice == 5:
display()
elif choice == 6:
print("Exiting program.")
break
else:
print("Invalid choice! Try again.")

# **Q16. MySQL – Table: LAB**

### a. Create table LAB

```sql
CREATE TABLE LAB (
No INT,
ItemName VARCHAR(30),
CostPerItem INT,
Quantity INT,
Warranty INT,
Operational INT
);
```

### b. Insert values

```sql
INSERT INTO LAB VALUES
(1, 'Computer', 60000, 9, 2, 7),
(2, 'Printer', 15000, 3, 4, 2),
(3, 'Scanner', 18000, 1, 3, 1),
(4, 'Camera', 21000, 2, 1, 1);
```
### c. Update Quantity of Printer to 10

```sql
UPDATE LAB
SET Quantity = 10
WHERE ItemName = 'Printer';
```

### d. Arrange table based on ItemName in Desc order

```sql
SELECT * FROM LAB
ORDER BY ItemName DESC;
```

### e. Display ItemName where CostPerItem > 20000

```sql
SELECT ItemName FROM LAB
WHERE CostPerItem > 20000;
```

### f. Display ItemNames with 2 years Warranty

```sql
SELECT ItemName FROM LAB
WHERE Warranty = 2;
```

---

# **Q17. MySQL – Table: SPORTS**

### a. Create table SPORTS

```sql
CREATE TABLE SPORTS (
GCode INT,
GameName VARCHAR(30),
No_Players INT,
PrizeMoney INT
);
```

### b. Insert values

```sql
INSERT INTO SPORTS VALUES
(101, 'Carom Board', 2, 5000),
(102, 'Table Tennis', 2, 12000),
(103, 'Lawn Tennis', 4, 8000),
(105, 'Chess', 2, 9000),
(108, 'Table Tennis', 4, 25000);
```

### c. Count players enrolled for each game

```sql
SELECT GameName, SUM(No_Players) AS TotalPlayers
FROM SPORTS
GROUP BY GameName;
```

### d. Alter table → add DATE column

```sql
ALTER TABLE SPORTS ADD COLUMN GameDate DATE;

-- Example updates
UPDATE SPORTS SET GameDate = '2025-01-01' WHERE GCode = 101;
UPDATE SPORTS SET GameDate = '2025-01-02' WHERE GCode = 102;
UPDATE SPORTS SET GameDate = '2025-01-03' WHERE GCode = 103;
UPDATE SPORTS SET GameDate = '2025-01-04' WHERE GCode = 105;
UPDATE SPORTS SET GameDate = '2025-01-05' WHERE GCode = 108;
```

### e. Count & sum PrizeMoney for Table Tennis

```sql
SELECT COUNT(*) AS Count_TT, SUM(PrizeMoney) AS TotalPrize
FROM SPORTS
WHERE GameName = 'Table Tennis';
```

### f. Display records in descending PrizeMoney

```sql
SELECT * FROM SPORTS
ORDER BY PrizeMoney DESC;
```

---

# **Q18. MySQL – Table: BOOKS**

### a. Create table BOOKS

```sql
CREATE TABLE BOOKS (
Book_Id VARCHAR(10),
Book_Name VARCHAR(50),
Publishers VARCHAR(30),
Price INT
);
```

### b. Insert values

```sql
INSERT INTO BOOKS VALUES
('F0001', 'The Tears', 'First Publ.', 750),
('F0002', 'Thunderbolt', 'First Publ.', 700),
('F0003', 'My First C++', 'EPB', 250),
('F0004', 'C++ Brain', 'TDH', 325),
('F0005', 'Fast Cook', 'EPB', 350);
```

### c. Display Max & Min price publisher-wise


```sql
SELECT Publishers, MAX(Price) AS MaxPrice, MIN(Price) AS MinPrice
FROM BOOKS
GROUP BY Publishers;
```

### d. Alter table → add QUANTITY column

```sql
ALTER TABLE BOOKS ADD COLUMN Quantity INT(5);

-- Example updates
UPDATE BOOKS SET Quantity = 10 WHERE Book_Id = 'F0001';
UPDATE BOOKS SET Quantity = 20 WHERE Book_Id = 'F0002';
UPDATE BOOKS SET Quantity = 15 WHERE Book_Id = 'F0003';
UPDATE BOOKS SET Quantity = 12 WHERE Book_Id = 'F0004';
UPDATE BOOKS SET Quantity = 8 WHERE Book_Id = 'F0005';
```

### e. Display books in ascending Book_Name

```sql
SELECT * FROM BOOKS
ORDER BY Book_Name ASC;
```

### f. Delete record with Book_Id = F0001

```sql
DELETE FROM BOOKS
WHERE Book_Id = 'F0001';
```

# **Q21. STUDENT Table**

### SQL Part

```sql
-- a) Create the STUDENT table
CREATE TABLE STUDENT (
Sno INT,
Sname VARCHAR(30),
Gender CHAR(1),
Age INT,
Fees INT
);

-- b) Insert the given records


INSERT INTO STUDENT VALUES
(1, 'Ashish', 'M', 17, 6550),
(2, 'Madhulika', 'F', 20, 7124),
(3, 'Niti Singh', 'F', 21, 18000),
(4, 'Pratyush', 'M', 18, 1200),
(6, 'Anand Seth', 'M', 16, 19500);

-- c) Update Age to 20 for Student Number 4


UPDATE STUDENT
SET Age = 20
WHERE Sno = 4;

-- d) Display records arranged by Sname in Descending Order


SELECT * FROM STUDENT
ORDER BY Sname DESC;

-- e) Alter table to add a new column Course


ALTER TABLE STUDENT ADD COLUMN Course VARCHAR(20);

-- Updating Course values


UPDATE STUDENT SET Course = 'C' WHERE Sno = 1;
UPDATE STUDENT SET Course = 'C++' WHERE Sno = 2;
UPDATE STUDENT SET Course = 'Java' WHERE Sno = 3;
UPDATE STUDENT SET Course = 'Python' WHERE Sno = 4;
UPDATE STUDENT SET Course = 'C#' WHERE Sno = 6;

-- f) Display Highest and Lowest Fees


SELECT MAX(Fees) AS HighestFees, MIN(Fees) AS LowestFees
FROM STUDENT;
```

### Python Connectivity Program

```python
import [Link]

# Connect to MySQL
con = [Link](host="localhost", user="root",
password="yourpassword", database="school")
cur = [Link]()

# Example: Display students


[Link]("SELECT * FROM STUDENT")
for row in [Link]():
print(row)

[Link]()
```

---

# **Q22. EMP Table**

### SQL Part

```sql
-- a) Create EMP table
CREATE TABLE EMP (
W_ID INT,
FIRSTNAME VARCHAR(20),
LASTNAME VARCHAR(20),
CITY VARCHAR(20),
SALARY INT
);

-- b) Insert given records


INSERT INTO EMP VALUES
(102, 'SAM', 'TONES', 'PARIS', 75000),
(105, 'SARAH', 'ACKERMAN', 'NEW YORK', 85000),
(144, 'MANILA', 'SENGUPTA', 'NEW DELHI', 70000),
(210, 'GEORGE', 'SMITH', 'PARIS', 75000),
(255, 'MARY', 'JONES', 'HUSTON', 50000);

-- c) Display employees from PARIS


SELECT * FROM EMP
WHERE CITY = 'PARIS';

-- d) Alter table to add Department column


ALTER TABLE EMP ADD COLUMN Department VARCHAR(20);

-- Updating Department values


UPDATE EMP SET Department = 'HR' WHERE W_ID = 102;
UPDATE EMP SET Department = 'SALES' WHERE W_ID = 105;
UPDATE EMP SET Department = 'ADMIN' WHERE W_ID = 144;
UPDATE EMP SET Department = 'HR' WHERE W_ID = 210;
UPDATE EMP SET Department = 'SALES' WHERE W_ID = 255;

-- e) Display highest & lowest salary department-wise


SELECT Department, MAX(SALARY) AS MaxSalary, MIN(SALARY) AS MinSalary
FROM EMP
GROUP BY Department;
```

### Python Connectivity Program

```python
import [Link]

con = [Link](host="localhost", user="root",


password="yourpassword", database="company")
cur = [Link]()

# Example: Display employees from Paris


[Link]("SELECT * FROM EMP WHERE CITY='PARIS'")
for row in [Link]():
print(row)

[Link]()
```

---

# **Q23. HOSPITAL Table**

### SQL Part

```sql
-- a) Create HOSPITAL table
CREATE TABLE HOSPITAL (
No INT,
Name VARCHAR(30),
Age INT,
Dept VARCHAR(20),
Doj DATE
);

-- b) Insert given records


INSERT INTO HOSPITAL VALUES
(1, 'Sam', 55, 'Surgery', '1998-01-23'),
(2, 'Rachel', 27, 'Orthopedic', '1998-02-20'),
(3, 'Ryan', 45, 'Orthopedic', '1998-01-13'),
(4, 'Tarun', 29, 'Surgery', '1998-03-28'),
(5, 'Tanya', 36, 'ENT', '1998-01-17');

-- c) Update charges of Surgery doctors from 300 → 500


-- Assuming a column Charges exists
ALTER TABLE HOSPITAL ADD COLUMN Charges INT;

UPDATE HOSPITAL SET Charges = 300 WHERE Dept='Surgery';


UPDATE HOSPITAL SET Charges = 500 WHERE Dept='Surgery';

-- d) Arrange records in ascending order of Doj


SELECT * FROM HOSPITAL
ORDER BY Doj ASC;

-- e) Count doctors with Age > 30


SELECT COUNT(*) AS DoctorsAbove30
FROM HOSPITAL
WHERE Age > 30;
```

### Python Connectivity Program

```python
import [Link]

con = [Link](host="localhost", user="root",


password="yourpassword", database="health")
cur = [Link]()

# Example: Doctors above 30


[Link]("SELECT COUNT(*) FROM HOSPITAL WHERE Age > 30")
print("Doctors above 30:", [Link]()[0])

[Link]()
```

---

# **Q24. STATIONERY Table**

### SQL Part

```sql
-- a) Create STATIONERY table
CREATE TABLE STATIONERY (
_ID VARCHAR(10),
SName VARCHAR(20),
Company VARCHAR(20),
Price INT
);

-- b) Insert given records


INSERT INTO STATIONERY VALUES
('DP01', 'Pen', 'ABC', 10),
('PL02', 'Pencil', 'XYZ', 6),
('ER05', 'Eraser', 'XYZ', 7),
('PL01', 'Pencil', 'CAM', 5),
('GP02', 'Gel Pen', 'ABC', 15);

-- c) Increase price of all items by Rs.2


UPDATE STATIONERY
SET Price = Price + 2;

-- d) Display maximum & minimum price company-wise


SELECT Company, MAX(Price) AS MaxPrice, MIN(Price) AS MinPrice
FROM STATIONERY
GROUP BY Company;

-- e) Delete records belonging to company 'CAM'


DELETE FROM STATIONERY
WHERE Company = 'CAM';
```

### Python Connectivity Program

```python
import [Link]

con = [Link](host="localhost", user="root",


password="yourpassword", database="store")
cur = [Link]()

# Example: Show stationery records


[Link]("SELECT * FROM STATIONERY")
for row in [Link]():
print(row)

[Link]()
```

Common questions

Powered by AI

The SQL approach for organizing book records by names involves using the ORDER BY clause in: SELECT * FROM BOOKS ORDER BY Book_Name ASC;. This command sorts the 'BOOKS' table entries based on the 'Book_Name' column in ascending order, thus enabling users to view records alphabetically. This ordering is crucial for efficient navigation and retrieval in applications like library databases .

The purpose of increasing prices systematically is often to adjust for inflation or increase revenue. In this SQL operation, the price is updated using: UPDATE STATIONERY SET Price = Price + 2;. This statement iterates over each record in the 'STATIONERY' table, adding 2 to the existing price value for each item, effectively ensuring all items reflect the new pricing policy .

The function 'modify_list' iterates through each element in a list. It checks if the element is even by using the modulus operator (num % 2 == 0). If true, it appends double the element's value to a new list. If the element is odd, it appends a third of the element's value as a float result. This process results in a new list reflecting these transformations .

The function ISTOUPCOUNT opens a file in read mode, reads its content, and splits it into words after converting all letters to uppercase to avoid case sensitivity issues. It then iterates over each word, using conditional checks to increment counters for each occurrence of the words 'IS', 'TO', and 'UP'. This method is significant for basic textual analysis, enabling the identification of frequently used keywords within documents .

The program implements a stack using a list and provides a menu-driven interface to perform operations such as PUSH (add an item), POP (remove the last added item), PEEK (view the last item without removing), SEARCH (find the position of an item), and DISPLAY (show all items in stack). These operations mimic typical stack behavior, adhering to Last In, First Out (LIFO) principles .

The program utilizes a try-except structure to handle file not found errors. Within the try block, it attempts file operations like reading. If the file doesn't exist, a FileNotFoundError is caught by the except block, displaying a user-friendly message like 'File not found.' This error handling is critical to prevent crashes during runtime, facilitate debugging, and provide users with clear feedback to rectify the problem .

Adding a 'GameDate' column allows for temporal analysis of sports events, enabling insights into scheduling patterns, seasonality, and event management. This facilitates queries that can sort and filter events by date and improve reporting capabilities about past and upcoming events. It enhances data analysis by providing a chronological framework for interpreting other metrics such as attendance or PrizeMoney .

The program uses the 'pickle' module to serialize student records by writing them to a binary file with pickle.dump(). For searching, it opens the file in read mode and uses pickle.load() within a loop to deserialize records one by one. This method is effective as it preserves complex object structures, allows efficient storage and retrieval, and facilitates quick searches by stopping at the first match found .

To handle these processes: First, create the table with: CREATE TABLE LAB ( No INT, ItemName VARCHAR(30), CostPerItem INT, Quantity INT, Warranty INT, Operational INT ); Then, insert records using: INSERT INTO LAB VALUES (1, 'Computer', 60000, 9, 2, 7), (2, 'Printer', 15000, 3, 4, 2), etc. Finally, update the quantity of an item, e.g., a Printer to 10 with: UPDATE LAB SET Quantity = 10 WHERE ItemName = 'Printer'; .

The program first writes employee data to a CSV file using csv.writer and then reads these records using csv.reader. When updating, it opens the current file for reading and a temporary file for writing. It iterates through existing records, modifying specific entries when an Employee ID matches the search criteria, and writes all updates to the temporary file. After processing, the old file is replaced with the updated file, ensuring that data is correctly altered while maintaining original structure .

You might also like