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

Assignment

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)
48 views14 pages

Assignment

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/ 14

1. **Word Count with Vowels in `story.

txt`**:

```python

def count_words_with_vowel():

with open("story.txt", "r") as file:

text = file.read()

words = text.split()

vowel_words = [word for word in words if any(vowel in word.lower() for vowel in 'aeiou')]

print(f"Words with vowels: {len(vowel_words)}")

print(vowel_words)

```

2. **Lines with 'A' to `target.txt`**:

```python

def copy_lines_starting_with_A():

with open("record.txt", "r") as source, open("target.txt", "w") as target:

for line in source:

if line.startswith("A"):

target.write(line)

```

3. **Count Occurrences of 'The' and 'an' in `story.txt`**:

```python

def count_the_and_an():

with open("story.txt", "r") as file:

text = file.read().lower()

the_count = text.split().count("the")

an_count = text.split().count("an")

print(f"'The' occurs {the_count} times.")

print(f"'An' occurs {an_count} times.")

```
4. **Student Data in `student.txt` with Update Function**:

```python

def create_student_file():

students = [

{"roll": 1, "name": "Alice", "city": "CityA", "phone": "1234567890"},

# Add 9 more student entries here...

with open("student.txt", "w") as file:

for student in students:

file.write(f"{student['roll']},{student['name']},{student['city']},{student['phone']}\n")

def update_student_phone(name, new_phone):

found = False

lines = []

with open("student.txt", "r") as file:

lines = file.readlines()

with open("student.txt", "w") as file:

for line in lines:

parts = line.strip().split(',')

if parts[1] == name:

parts[3] = new_phone

found = True

file.write(','.join(parts) + "\n")

if not found:

print("Error: Student not found.")

```

5. **Copy Contents from `file1.txt` to `file2.txt`**:

```python

def copyfun(source, desti):

with open(source, "r") as src, open(desti, "w") as dst:


dst.write(src.read())

```

6. **Binary File `Book.dat` Functions**:

```python

import pickle

def CreateFile():

with open("Book.dat", "ab") as file:

record = {"BookNo": 1, "Book_Name": "Python101", "Author": "AuthorA", "Price": 1200}

pickle.dump(record, file)

def CountRect(author):

count = 0

with open("Book.dat", "rb") as file:

while True:

try:

record = pickle.load(file)

if record["Author"] == author:

count += 1

except EOFError:

break

return count

def Display():

count = 0

with open("Book.dat", "rb") as file:

while True:

try:

record = pickle.load(file)

if record["Price"] > 1000:


print(record)

count += 1

except EOFError:

break

print(f"Number of books with price over 1000: {count}")

```

7. **Update Mobile Numbers in `TELE.DAT`**:

```python

def update_mobile_numbers():

import pickle

records = []

with open("TELE.DAT", "rb") as file:

try:

while True:

record = pickle.load(file)

if record["mobile_no"].startswith("8"):

record["mobile_no"] = "7" + record["mobile_no"][1:]

records.append(record)

except EOFError:

pass

with open("TELE.DAT", "wb") as file:

for record in records:

pickle.dump(record, file)

```

8. **Student Data File with Percentage Calculation**:

```python

def write_data():

import pickle

students = [{"rollno": 1, "name": "John", "M_Physics": 85, "M_Chemistry": 90, "M_Maths": 95}]
for student in students:

student["Per"] = (student["M_Physics"] + student["M_Chemistry"] + student["M_Maths"]) / 3

with open("Stud.dat", "wb") as file:

for student in students:

pickle.dump(student, file)

```

9. **Write Books to `record.csv`**:

```python

import csv

def write_books_to_csv():

with open("record.csv", "w", newline="") as file:

writer = csv.writer(file)

writer.writerow(["bno", "bname", "author", "price", "quantity"])

while True:

bno = input("Enter book number: ")

if bno.lower() == 'n':

break

bname = input("Enter book name: ")

author = input("Enter author: ")

price = input("Enter price: ")

quantity = input("Enter quantity: ")

writer.writerow([bno, bname, author, price, quantity])

```

10. **Read Data from `record.csv`**:

```python

def read_books_from_csv():

import csv

with open("record.csv", "r") as file:


reader = csv.reader(file)

next(reader)

max_quantity = 0

max_book = None

for row in reader:

quantity = int(row[4])

if quantity > max_quantity:

max_quantity = quantity

max_book = row

print(f"Book with highest quantity: {max_book[1]}, Author: {max_book[2]}")

```

===========

SQL Assignment Solutions


Question 1 - STUDENT and COURSE Tables
Total number of students registered:

SELECT COUNT(*) AS TotalStudents FROM STUDENT;

Total fees collected by the institution:

SELECT SUM(FEES) AS TotalFees FROM COURSE;

Number of students registered in each course:

SELECT Course, COUNT(*) AS StudentsCount FROM STUDENT GROUP BY Course;

Name of students trained by Anadi Singh:

SELECT Sname FROM STUDENT


JOIN COURSE ON STUDENT.Course = COURSE.CNAME
WHERE Instructor = 'Anadi Singh';
Question 2 - EMPLOYEE and DEPARTMENT Tables
Number of records including null values:

SELECT COUNT(*) AS TotalRecords FROM EMPLOYEE;

Number of records excluding null in the city column:

SELECT COUNT(City) AS NonNullCityCount FROM EMPLOYEE;

Number of unique cities in the EMPLOYEE table:

SELECT COUNT(DISTINCT City) AS UniqueCities FROM EMPLOYEE;

Records grouped by city:

SELECT * FROM EMPLOYEE GROUP BY City;

=================

1. **Function `MakePush(Package)` and `MakePop(Package)` for Stack Operations**:

```python

stack = [] # Stack to store package descriptions

def MakePush(package):

"""Push a new package onto the stack."""

stack.append(package)

print(f"Package '{package}' added to the stack.")

def MakePop():

"""Pop a package from the stack."""

if len(stack) > 0:

removed_package = stack.pop()
print(f"Package '{removed_package}' removed from the stack.")

return removed_package

else:

print("Error: Stack is empty.")

return None

```

2. **Function `PUSH(Arr)` to Push Numbers Divisible by 5**:

```python

def PUSH(Arr):

stack = [] # Stack to store numbers divisible by 5

for number in Arr:

if number % 5 == 0:

stack.append(number)

if len(stack) > 0:

print("Stack with numbers divisible by 5:", stack)

else:

print("Error: No elements divisible by 5 in the list.")

```

3. **Function `POP(Arr)` to Pop Elements from the Stack**:

```python

def POP(Arr):

if len(Arr) > 0:

removed_value = Arr.pop()

print(f"Value '{removed_value}' popped from the stack.")

return removed_value

else:

print("Error: Stack is empty.")

return None

```
==========

pip install mysql-connector-python

```

Each code block includes a connection setup. Make sure to replace `'your_username'`,
`'your_password'`, `'localhost'`, and `'record'` (or `'school'`) with your actual database credentials.

### 1. Retrieve Students with Marks > 95% in Physics and Chemistry

```python

import mysql.connector

def fetch_high_scorers():

conn = mysql.connector.connect(

host='localhost',

user='your_username',

password='your_password',

database='record'

cursor = conn.cursor()

query = """

SELECT * FROM students

WHERE Physics > 95 AND Chemistry > 95;

"""

cursor.execute(query)

result = cursor.fetchall()

for row in result:


print(row)

cursor.close()

conn.close()

fetch_high_scorers()

```

### 2. Retrieve One Record at a Time from `Employee` Table for Employees Living in Delhi

```python

import mysql.connector

def fetch_employees_in_delhi():

conn = mysql.connector.connect(

host='localhost',

user='your_username',

password='your_password',

database='record'

cursor = conn.cursor()

query = """

SELECT * FROM Employee

WHERE City = 'Delhi';

"""

cursor.execute(query)

row = cursor.fetchone()

while row is not None:


print(row)

row = cursor.fetchone()

cursor.close()

conn.close()

fetch_employees_in_delhi()

```

### 3. Insert a Record into the `doctor` Table

```python

import mysql.connector

def insert_doctor_record():

conn = mysql.connector.connect(

host='localhost',

user='your_username',

password='your_password',

database='record'

cursor = conn.cursor()

# Prompt user input

DID = input("Enter Doctor ID: ")

Dname = input("Enter Doctor Name: ")

Area = input("Enter Area: ")

query = """

INSERT INTO doctor (DID, Dname, Area)

VALUES (%s, %s, %s);


"""

data = (DID, Dname, Area)

cursor.execute(query, data)

conn.commit()

print("Record inserted successfully.")

cursor.close()

conn.close()

insert_doctor_record()

```

### 4. Update Salary by 10% for Employees Whose Name Starts with 'A' and Has 'h' as the Third
Letter

```python

import mysql.connector

def update_salary():

conn = mysql.connector.connect(

host='localhost',

user='your_username',

password='your_password',

database='record'

cursor = conn.cursor()

query = """

UPDATE Employee
SET Salary = Salary * 1.10

WHERE Name LIKE 'A_h%';

"""

cursor.execute(query)

conn.commit()

print("Salary updated successfully for eligible employees.")

cursor.close()

conn.close()

update_salary()

```

### 5. Delete a Record from `student` Table in `school` Database Where Name = 'Mayur'

```python

import mysql.connector

def delete_student_record():

conn = mysql.connector.connect(

host='localhost',

user='your_username',

password='your_password',

database='school'

cursor = conn.cursor()

query = """

DELETE FROM student


WHERE Name = 'Mayur';

"""

cursor.execute(query)

conn.commit()

print("Record deleted successfully.")

cursor.close()

conn.close()

delete_student_record()

```

You might also like