0% found this document useful (0 votes)
13 views13 pages

CS Boards Pracs

The document contains various Python code snippets demonstrating different programming concepts such as sorting, searching, data manipulation, and file handling. Key functionalities include bubble sort, binary search, data insertion and deletion, matrix operations, and reading/writing to text and binary files. Additionally, it showcases how to work with CSV files and dictionaries for employee records and frequency counting of characters in a string.

Uploaded by

nirangini.s
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)
13 views13 pages

CS Boards Pracs

The document contains various Python code snippets demonstrating different programming concepts such as sorting, searching, data manipulation, and file handling. Key functionalities include bubble sort, binary search, data insertion and deletion, matrix operations, and reading/writing to text and binary files. Additionally, it showcases how to work with CSV files and dictionaries for employee records and frequency counting of characters in a string.

Uploaded by

nirangini.s
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
You are on page 1/ 13

#bubble sort

'''
def bubble():
l=[1,6,-3,5,6,]
for i in range(len(l)-1):
for j in range(0,len(l)-1-i):
if l[j]>l[j+1]:
l[j],l[j+1]=l[j+1],l[j]
print(l)
bubble()
'''

#delete a data
'''
def del_data():
l=[1,2,3,4,5]
d=int(input("enter the data to delete"))
while d in l:
l.remove(d)
print(l)
del_data()
'''

#swap alternate values


'''
def swap_alternate():
l=[1,2,3,4,5]
for i in range(0,len(l)-1,2):
l[i],l[i+1]=l[i+1],l[i]
print(l)
swap_alternate()
'''
#binary search
'''
l=[1,2,3,4,5,6,100]
lb=0;
ub=len(l)-1
mid=(lb+ub)//2
pos=-1
d=int(input("enter the data to find"))
while lb<=ub and pos==-1:
if d==l[mid]:pos=mid+1
elif d<l[mid]:ub=mid-1
else:lb=mid+1
mid=(lb+ub)//2
if (pos==-1):print("data not found")
else:print("data found at pos",pos)
'''
#swap half of list
'''
def swap_list():
l=[1,2,3,4,5,6,7,8,9,10]
mid = len(l) // 2
c=l[mid:] + l[:mid]
print(c)
swap_list()
'''
#insert a data
'''
def ins_data():
l=[1,2,3,4,5]
d=int(input("enter the data to insert"))
n=int(input("after which number to insert the data"))
for i in l:
if i==n:
l.insert(i,d)
print(l)
ins_data()
'''
#sum diagnol boundary upper and lower triangle
'''
M = int(input("Enter number of rows: "))
N = int(input("Enter number of columns: "))
T = tuple(tuple(int(input("Enter integer: ")) for j in range(N)) for i in range(M))

def sum_rc():
for i in range(M):
s = 0
for j in range(N):
s += T[i][j]
print("The sum of row", i + 1, "is", s)
print()
for j in range(N):
s = 0
for i in range(M):
s += T[i][j]
print("The sum of column", j + 1, "is", s)
print()

def ld():
s = 0
for i in range(M):
for j in range(N):
if i == j:
s += T[i][j]
print("the sum of left diagnols is",s)

def rd():
s = 0
for i in range(M):
for j in range(N):
if i + j == M - 1:
s += T[i][j]
print("sum of right diagnols is",s)

print("\n boundary")

def boundary():
for i in range(M):
for j in range(N):
if i == 0 or i == M - 1 or j == 0 or j == N - 1:
print(T[i][j], end=" ")
else:
print(" ", end=" ")
print()
def upper():
print("\nupper triangle")
for i in range(M):
for j in range(N):
if i<=j:
print(T[i][j],end=" ")
else:
print(" ",end=" ")
print()
print("\nlower triangle")

def lower():
print("\nlower triangle")
for i in range(M):
for j in range(N):
if i>=j:
print(T[i][j],end="")
else:print(" ",end=" ")
print()

sum_rc()
ld()
rd()
boundary()
upper()
lower()
'''
#dict=total count update
'''
# Accepting employee records
employees = {}

for _ in range(5):
roll_no = int(input("Enter Roll Number: "))
name = input("Enter Name: ")
salary = float(input("Enter Salary: "))
employees[roll_no] = [name, salary]

def TOTAL():
total_salary = 0
for emp in employees.values():
total_salary += emp[1] # Adding salary manually
print("\nTotal Salary of all employees:", total_salary)

def Update():
for emp in employees.values():
emp[1] *= 1.10 # Directly updating salary using values()
print("\nSalaries updated successfully!")

def Count():
count = 0
for emp in employees.values():
if emp[1] > 10000: # Checking salary condition
count += 1
print("\nNumber of employees with salary above 10,000:", count)
# Function Calls
TOTAL()
Update()
TOTAL() # Check updated salary
Count()
'''
#frequency of streng

'''

def freq():
d = {} # Dictionary to store frequency of letters
for c in s: # Loop through each character in the sentence
if c.isalpha(): # Only consider alphabets
d.setdefault(c, 0) # If 'c' is not in d, set it to 0
d[c] += 1 # Increment count

print("\nLetter Frequency:")
for k, v in d.items(): # Print all letter frequencies
print(k, ":", v) # Printing without f-strings

def count():
num_words = 0
num_uppercase = 0
num_lowercase = 0
num_digits = 0
num_others = 0

words = s.split() # Split the sentence into words

for word in words:


num_words += 1 # Count the words

for char in word:


if char.isupper():
num_uppercase += 1 # Count uppercase letters
elif char.islower():
num_lowercase += 1 # Count lowercase letters
elif char.isdigit():
num_digits += 1 # Count digits
else:
num_others += 1 # Count other characters

print("Total Words:", num_words)


print("Uppercase Letters:", num_uppercase)
print("Lowercase Letters:", num_lowercase)
print("Digits:", num_digits)
print("Other Characters:", num_others)

def count_uppercase_vowel():
vowels = "AEIOU"
count = 0

words = s.split() # Split sentence into words

for word in words:


if word[0].upper() in vowels: # Check if the first letter is an uppercase
vowel
count += 1 # Increment the count
print("\nNumber of words starting with an uppercase vowel:", count)

def count_the():
c=0
for i in s.split():
if i=="the":c=+1
print("the number of the is",c)

def count_wc():
w=0;c=0
for i in s.split():
w+=1
for i in s:
c+=1
print(w,c)

# Accepting the sentence from the user


s = input("Enter a sentence: ")

# Calling the functions


freq()
count()
count_uppercase_vowel()
count_the()
count_wc()
'''
#board.txt
'''
# Creating a text file called BOARD.TXT and writing content
with open("BOARD.TXT", "w") as file:
file.write("This is a sample file. The content includes words like The, THE,
and more.\n")
file.write("Let's test the functionality with a few more lines.\n")
file.write("The program is designed to count and transfer.\n")

# Function a: Count number of words, lines, and characters


def count():
with open("BOARD.TXT", "r") as file:
text = file.read()

print("File Contents:")
print(text)

lines = text.count("\n") + 1 # Add 1 for the last line


words = len(text.split())
chars = len(text)

print("Lines:", lines)
print("Words:", words)
print("Characters:", chars)

# Function b: Transfer Uppercase alphabets into a list and display the list
def transfer():
with open("BOARD.TXT", "r") as file:
text = file.read()

uppercase = []
for char in text:
if char.isupper():
uppercase.append(char)

print("Uppercase letters:", uppercase)

# Function c: Count number of occurrences of the word "The" for whole file
def count_the():
with open("BOARD.TXT", "r") as file:
text = file.read()

the_count = text.lower().split().count("the")
print("The appears", the_count, "times.")

#the and The for each line

def count_the1():
with open("BOARD.TXT", "r") as file:
line_number = 1
line = file.readline()

while line:
the_count = line.split().count("the")
The_count = line.split().count("The")
print("In line", line_number, "'the' appears", the_count, "time(s).")
print("In line", line_number, "'The' appears", The_count, "time(s).")
line_number += 1 # Increment the line number after processing the
current line
line = file.readline()

def count1():
with open("BOARD.TXT", "r") as file:
text = file.read() # Read the entire content at once

uppercase = 0
lowercase = 0
digits = 0
others = 0

for char in text:


if char.isupper():
uppercase += 1
elif char.islower():
lowercase += 1
elif char.isdigit():
digits += 1
else:
others += 1

print("Uppercase alphabets:", uppercase)


print("Lowercase alphabets:", lowercase)
print("Digits:", digits)
print("Other characters:", others)

def transfer_1st_last():

with open("board.txt", 'r') as f:


l = []
line = f.readline()
while line:
words = line.split()
if words:
l.append(words[0])
l.append(words[-1])
line = f.readline()

print(l)

count()
transfer()
count_the()
count_the1()
count1()
transfer_1st_last()

'''
#binary files

'''
import pickle
import os

def create():
f = open("abc.dat", "wb")
name = input("Enter the name: ")
age = int(input("Enter the age: "))
salary = int(input("Enter the salary: "))
l = [name, age, salary]
pickle.dump(l, f)
f.close()

def display():
f = open("abc.dat", 'rb')
found = True
while found:
try:
data = pickle.load(f)
except EOFError:
found = False
else:
print("Name:", data[0])
print("Age:", data[1])
print("Salary:", data[2])
f.close()

def modify():
f = open("abc.dat", 'rb')
g = open("emp.dat", 'wb')
d = input("Enter the name of the person's record you want to modify: ")
found = True
while found:
try:
data = pickle.load(f)
except EOFError:
found = False
else:
if d == data[0]:
age = int(input("Enter the age: "))
salary = int(input("Enter the salary: "))
l = [data[0], age, salary]
pickle.dump(l, g)
else:
pickle.dump(data, g)
f.close()
g.close()
os.remove("abc.dat")
os.rename("emp.dat", "abc.dat")

def add_arecord():
f = open("abc.dat", 'ab')
n = int(input("Enter how many more records you want to enter: "))
for i in range(n):
name = input("Enter the name: ")
age = int(input("Enter the age: "))
salary = int(input("Enter the salary: "))
l = [name, age, salary]
pickle.dump(l, f)
f.close()

def update():
f = open("abc.dat", 'rb')
g = open("emp.dat", 'wb')
found = True
while found:
try:
data = pickle.load(f)
except EOFError:
found = False
else:
data[2] *= 1.10 # Assuming you want to increase salary by 1%
pickle.dump(data, g)
f.close()
g.close()
os.remove('abc.dat')
os.rename('emp.dat', 'abc.dat')

def insert():
f = open("abc.dat", 'rb')
g = open("emp.dat", 'wb')
d = input("Enter after which record to insert: ")
found = True
while found:
try:
data = pickle.load(f)
except EOFError:
found = False
else:
if data[0] == d:
name = input("Enter the name: ")
age = int(input("Enter the age: "))
salary = int(input("Enter the salary: "))
l = [name, age, salary]
pickle.dump(data, g)
pickle.dump(l, g)
else:
pickle.dump(data, g)
f.close()
g.close()
os.remove('abc.dat')
os.rename('emp.dat', 'abc.dat')

def menu():
ch=1
while True:
print('\n 1.create\n2.display\n3.modify\n4.add a record\n5.update\
n6.insert')
ch=int(input("choose a number"))
if ch>=2 and ch<=6:
try:f=open("abc.dat",'rb')
except FileNotFoundError:print("FIRST choose OPTION 1")
else:
f.close()
if ch==2:display()
elif ch==3:modify()
elif ch==4:add_arecord()
elif ch==5:update()
elif ch==6:insert()
elif ch==1:create()

menu()
'''
#csv file
'''
import csv
def create():
f=open('book.csv','w',newline='')
csvobj=csv.writer(f,delimiter=',')
for i in range(2):
bc=int(input("enter the book code"))
bn=input("enter book name")
bs=int(input("enter the book cost"))
l=[bc,bn,bs]
csvobj.writerow(l)
f.close()

def count():
f=open('book.csv','r',newline='')
data =csv.reader(f)
c=0
for i in data:
if float(i[2]) <100:c+=1
f.close()
print(c)

def transfer():
f=open('book.csv','r',newline='');l=[]
data=csv.reader(f)
for i in data:
if float(i[2])<100:
l.append(i)
f.close()
print(l)
create()
count()
transfer()
'''
#transfer from the list_csv
'''

import csv

# Function to transfer the list of tuples to a CSV file called ABC.CSV


def t():
d = [
("John", 8, "Male"),
("Alice", 12, "Female"),
("Bob", 6, "Male"),
("Charlie", 15, "Male"),
("Diana", 9, "Female")
]

with open('ABC.CSV', 'w', newline='') as f:


w = csv.writer(f)
w.writerow(["Name", "Age", "Gender"])

for r in d:
w.writerow(r)

print("Data has been transferred to ABC.CSV.")

def d():
with open('ABC.CSV', 'r') as f:
r = csv.reader(f)
for row in r :
print(row)

# Function to count the number of records whose age is below 10


def c():
count = 0
with open('ABC.CSV', 'r') as f:
r = csv.reader(f)
for row in r[1:]:
if int(row[1]) < 10:
count += 1
print(f"Number of records with age below 10: {count}")
def m():
while True:
print("\nMenu:")
print("1. Transfer data to ABC.CSV")
print("2. Display contents of ABC.CSV")
print("3. Count records with age below 10")
print("4. Exit")

choice = int(input("Enter your choice: "))

if choice == 1:
t()
elif choice == 2:
d()
elif choice == 3:
c()
elif choice == 4:
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")

if __name__ == "__main__":
m()
'''
#mysql
'''
import mysql.connector

# Connect to the MySQL database


sqlobj = mysql.connector.connect(
host="localhost", # your MySQL host
user="root", # your MySQL username
password="password", # your MySQL password
database="mysql" # your MySQL database
)

pyobj = sqlobj.cursor()

# Create a table
pyobj.execute("CREATE TABLE exam (roll_no INT PRIMARY KEY, name VARCHAR(15), age
INT)")

# Insert multiple records into the table


pyobj.executemany(
"INSERT INTO exam (roll_no, name, age) VALUES (%s, %s, %s)",
[
(1, "Kala", 12),
(2, "Mala", 15),
(3, "Latha", 9)
]
)

# Delete a record from the table


pyobj.execute("DELETE FROM exam WHERE name = 'Latha'")

# Update records in the table


pyobj.execute("UPDATE exam SET age = age + 1")

# Fetch and display all records from the table


pyobj.execute("SELECT * FROM exam")
d = pyobj.fetchall()
c = 0
for i in d:
print(i)
c += 1
print(f"Total records: {c}")

# Drop the table


pyobj.execute("DROP TABLE exam")

# Commit the changes


sqlobj.commit()

# Close the cursor and connection


pyobj.close()
sqlobj.close()
'''
#STACK
'''
def stack(st):
ST.append(st)

def is_empty():
if ST == []:
return True
else:
return False

def pop(ST):
if is_empty() == True:
print("Underflow error")
else:
print("Data popped", ST.pop())

def display(ST):
if is_empty() == True:
print("No data")
else:
print("Stack contents:", ST[::-1])

def Pop_all(ST):
if is_empty() == True:
print("Underflow error")
else:
i = 0
while ST:
print("Data popped", ST.pop())
print("Empty stack")

def peek(ST):
if is_empty() == True:
print("No data")
else:
print("Peek data", ST[-1])

def Transfer():
L = [input("Enter string: ") for _ in range(5)]
for word in L:
if word[0].lower() in "aeiou":
stack(word)

ST = []

while True:
print("\nMenu:\n1. Transfer\n2. Pop\n3. Display\n4. Pop All\n5. Peek\n6. Exit")
choice = input("Enter choice: ")

if choice == "1":
Transfer()
elif choice == "2":
pop(ST)
elif choice == "3":
display(ST)
elif choice == "4":
Pop_all(ST)
elif choice == "5":
peek(ST)
elif choice == "6":
break
else:
print("Invalid choice")

'''
#tuples
'''
def Transfer_one(l):
N = len(l)
result = []
for i in range(N):
row = []
for j in range(N):
if j <= i:
row.append(l[j])
else:
row.append(0)
result.append(row)

# Printing the result in a triangular format using format


for row in result:
print(" ".join("{}".format(x) for x in row))

def Transfer_two(l):
N = len(l)
result = []
for i in range(N):
row = []
for j in range(N):
if j >= N - i - 1:
row.append(l[j])
else:
row.append(0)
result.append(row)

# Printing the result in a triangular format using format


for row in result:
print(" ".join("{}".format(x) for x in row))

l = [8, 2, 3, 4, 7]
Transfer_one(l)
print()
Transfer_two(l)
'''

You might also like