0% found this document useful (0 votes)
5 views

CS PROGRAM FILE (SOLVED)

Uploaded by

obanerjee265
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

CS PROGRAM FILE (SOLVED)

Uploaded by

obanerjee265
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

INDEX OF CONTENTS

SR No Title Signature Signature


(Teacher) (Examiner)

PYTHON PROGRAMS

1 PROGRAM TO READ A LINE AND PRINT NO.


OF UPPERCASE, LOWERCASE, DIGITS AND
ALPHABETS.

2 PROGRAM TO CALCULATE NO. OF WORDS,


CHARACTERS AND PERCENTAGE OF
CHARACTERS THAT ARE ALPHA NUMERIC.

3 PROGRAM TO SORT A LIST USING BUBBLE


SORT.

4 PROGRAM TO SORT A LIST USING INSERTION


SORT.

5 PROGRAM TO READ A STRING AND CHECK


WHETHER IT IS PALLINDROME OR NOT.

6 PROGRAM TO ROTATE THE ELEMENTS OF A


LIST.

7 PROGRAM TO PRINT THE LONGEST WORD IN


LIST OF WORDS.

8 PROGRAM TO GENERATE A RANDOM


NUMBER IN A GIVEN RANGE THRICE.

9 PROGRAM TO WRITE A PYTHON FUNCTION


SIN(X,N) TO CALCULATE THE VALUE OF
SIN(X) USING TAYLORS SERIES EXPANSION
UPTO ‘N’ TERMS.
10 PROGARM TO FIND MINIMUM ONE’S DIGIT IN
TWO NUMBERS.

11 PROGRAM TO READ A FILE LINE BY LINE AND


PRINT IT.

12 PROGRAM TO COUNT WORDS ‘TO’ AND ‘THE’


IN A TEXT FILE.

13 PROGRAM TO CONVERT BINARY NUMBER TO


DECIMAL

14 PROGRAM TO CONVERT OCTAL NUMBER TO


DECIMAL

15 PROGRAM TO WRITE DATA TO CSV FILE.

16 PROGRAM TO PERFORM BINARY SEARCH IN


AN ARRAY.
MYSQL COMMANDS
Create a Database and Table(s) in MySQL and
perform the following:

1 Write a MySQL Query using 'AND'

2 Write a MySQL Query using 'OR'

3 Write a MySQL Query using 'NOT'

4 Write a MySQL Query using 'BETWEEN'

5 Write a MySQL Query using 'IN'

6 Write a MySQL Query using 'LIKE'

7 Write a MySQL Query using 'DISTINCT'

8 Write a MySQL Query using 'COUNT'

9 Write a MySQL Query using 'HAVING'

10 Write a MySQL Query using 'ORDER BY'

11 Write a MySQL Query using 'GROUP BY'

12 Write a MySQL Query using 'MAX', 'MIN', 'AVG'


# PROGRAM 1:- TO READ THE LINE AND COUNT AND PRINT
THE NUMBER
OFUPPERCASE, LOWERCASE, DIGITS AND ALPHABETS.

line = input("Enter a line: ")


lowercount = uppercount = digitcount = alphacount = 0

for a in line:
if a.islower():
lowercount += 1
elif a.isupper():
uppercount += 1
elif a.isdigit():
digitcount += 1

# Alphabets include both uppercase and lowercase letters


alphacount = lowercount + uppercount

print("Number of uppercase letters:", uppercount)


print("Number of lowercase letters:", lowercount)
print("Number of alphabets:", alphacount)
print("Number of digits:", digitcount)
Output:

Enter a line: FarrinGtoN15


Number of uppercase letters: 3
Number of lowercase letters: 7
Number of alphabets: 10
Number of digits: 2
# PROGRAM 2:- TO CALCULATE NUMBER OF WORDS,
CHARACTERS AND
PERCENTAGE OF CHARACTERS THAT ARE ALPHA NUMERIC.
s = input("Enter a string and press enter: ")

# Count the number of words


print("Number of words =", len(s.split()))

# Count the total number of characters


l = len(s)
print("Number of characters =", l)

# Count the number of alphanumeric characters


t=0
for i in s:
if i.isalnum():
t += 1

# Calculate the percentage of alphanumeric characters


if l > 0: # Avoid division by zero
p = (t / l) * 100
else:
p=0

print("Percentage of alphanumeric characters =", p, "%")


output:

Enter a string and press enter: Astoria Farrington


Number of words = 2
Number of characters = 18
Percentage of alphanumeric characters = 94.44444444444444 %
# PROGRAM 3: TO SORT A LIST USING BUBBLE SORT.

alist = [23, 5, 72, 45, 12, 3, 9]


print("Original list is:", alist)

n = len(alist)
for i in range(n):
for j in range(0, n - i - 1):
if alist[j] > alist[j + 1]:
# Swap the elements
alist[j], alist[j + 1] = alist[j + 1], alist[j]

print("List after sorting:", alist)

Output:

Original list is: [23, 5, 72, 45, 12, 3, 9]


List after sorting: [3, 5, 9, 12, 23, 45, 72]
# PROGRAM 4: TO SORT A SEQUENCE USING INSERTION SORT.

alist = [15, 6, 13, 22, 3, 52, 2]


print("Original list is:", alist)

# Insertion Sort Algorithm


for i in range(1, len(alist)):
key = alist[i]
j=i-1
while j >= 0 and key < alist[j]:
alist[j + 1] = alist[j]
j -= 1
alist[j + 1] = key # Place the key in its correct position

print("List after sorting:", alist)

Output:

Original list is: [15, 6, 13, 22, 3, 52, 2]


List after sorting: [2, 3, 6, 13, 15, 22, 52]
# PROGRAM 5: TO READ A STRING AND CHECK WHETHER IT
IS PALINDROME OR NOT.

string = input("Enter a string: ")


n = len(string)
rev = ''

# Reversing the string


for i in range(n - 1, -1, -1):
rev = rev + string[i]

# Checking for palindrome


if rev == string:
print("IT IS A PALINDROME")
else:
print("IT IS NOT A PALINDROME")

Output:

Enter a string: Mahalaya


IT IS NOT A PALINDROME

Enter a string: 121


IT IS A PALINDROME
# PROGRAM 6:- TO ROTATE THE ELEMENTS OF A LIST

l = []
lr = []

# Input for the number of elements in the list


n = int(input("Enter the number of elements in the list: "))

# Adding elements to the original list


for i in range(n):
s = int(input(f"Enter number {i + 1}: "))
l.append(s)

print("Original list is:", l)

# Reversing the list manually


for j in range(-1, -n - 1, -1):
lr.append(l[j])

print("Reversed list is:", lr)


Output:

Enter the number of elements in the list: 8


Enter number 1: 8
Enter number 2: 5
Enter number 3: 1
Enter number 4: 88
Enter number 5: 22
Enter number 6: 15
Enter number 7: 33
Enter number 8: 25
Original list is: [8, 5, 1, 88, 22, 15, 33, 25]
Reversed list is: [25, 33, 15, 22, 88, 1, 5, 8]
# PROGRAM 7: TO PRINT THE LONGEST WORD IN THE LIST
OF WORDS.

a = []
n = int(input("Enter the number of elements in the list: "))

# Input the elements of the list


for x in range(0, n):
element = input("Enter element " + str(x + 1) + ": ")
a.append(element)

# Initialize variables to find the word with the longest length


max1 = len(a[0])
temp = a[0]

for i in a:
if len(i) > max1:
max1 = len(i)
temp = i

print("The word with the longest length is:", temp)


Output:

Enter the number of elements in the list: 10


Enter element 1: 1
Enter element 2: 5
Enter element 3: 3
Enter element 4: 6
Enter element 5: 7
Enter element 6: 8
Enter element 7: 1
Enter element 8: 2
Enter element 9: 6
Enter element 10: 9
The word with the longest length is: 1
# PROGRAM 8: GENERATE A RANDOM NUMBER IN A GIVEN
RANGE THRICE. import random

def rand(n, m):


s = random.randint(n, m)
return s

a = int(input("Enter the starting value of range: "))


b = int(input("Enter the ending value of range: "))

for i in range(3):
print("Random number generated is:", rand(a, b))

Output:

Enter the starting value of range: 10


Enter the ending value of range: 50
Random number generated is: 35
Random number generated is: 16
Random number generated is: 37
# PROGRAM 9:- TO WRITE A PYTHON FUNCTION SIN(X,N) TO
CALCULATE THE VALUEOF SIN(X) USING TAYLORS SERIES
EXPANSION UPTO ‘N’ TERMS.

from math import pi

# Factorial function
def fac(x):
f=1
for i in range(1, x + 1):
f *= i
return f

# Sine function using Taylor series


def sin(x, n):
s=0
ctr = 0
for i in range(1, n + 1, 2): # Odd powers only
ctr += 1
s += ((-1) ** (ctr + 1)) * (x ** i) / fac(i)
return s

# Example usage
print(sin(pi / 2, 5))
Output:

1.0045248555348174
# PROGRAM 10: MINIMUM ONE’S DIGIT IN TWO NUMBERS.
def comp(a, b):

a1 = a % 10 # Get the one's digit of a


b1 = b % 10 # Get the one's digit of b

if a1 < b1:
return a
elif b1 < a1:
return b
else:
return 0

# Input for the two numbers


n1 = int(input("Enter the first number: "))
n2 = int(input("Enter the second number: "))

# Compare the ones digits of the two numbers


ans = comp(n1, n2)

# Output the result


if ans == 0:
print("Both have the same one's digit")
else:
print(f"{ans} has the minimum value of one's digit")
Output:

Enter the first number: 5


Enter the second number: 6
5 has the minimum value of one's digit

Enter the first number: 12


Enter the second number: 42
Both have same one's digit
# PROGRAM 11:-TO READ A FILE LINE BY LINE AND PRINT IT.

# CODE :-
f=open("poem.txt","r")
l=f.readlines()
for i in l:
print(i)

Output:

Where the mind is without fear and the head is held high

Where knowledge is free


Where the world has not been broken up into fragments

By narrow domestic walls

Where words come out from the depth of truth

Where tireless striving stretches its arms towards perfection

Where the clear stream of reason has not lost its way

Into the dreary desert sand of dead habit

Where the mind is led forward by thee

Into ever-widening thought and action

Into that heaven of freedom, my Father, let my country awake.


# PROGRAM 12:- TO COUNT WORDS ‘TO’ AND ‘THE’ IN A TEXT
FILE.

#code

text = open("poem.txt",'r')
word1="to"
word2="the"
c1=0
c2=0
for line in text:
words=line.split()
l=len(words)
for i in range(0,l):
s=words[i]
if s==word1:
c1=c1+1
if s==word2:
c2=c2+1
print("The word 'to' occurs",c1,"times")
print("The word 'the' occurs",c2,"times")

# OUTPUT:-

The word 'to' occurs 0 times


The word 'the' occurs 7 times
# PROGRAM 13:- TO CONVERT BINARY NUMBER TO DECIMAL
NUMBER.

b_num = list(input("Input a binary number: ")) # Convert input to


list of characters
value = 0

# Loop through the list from the end (most significant digit to
least significant)
for i in range(len(b_num)):
digit = b_num.pop() # Remove and get the last element (from
the right)
if digit == '1':
value = value + pow(2, i) # Add the corresponding power of 2
to the value

print("The decimal value of the number is", value)

Output:

Input a binary number: 0101


The decimal value of the number is 5
# PROGRAM 14: PROGRAM TO CONVERT OCTAL NUMBER TO
DECIMAL.

def octalToDecimal(n):
num = n
dec_value = 0
base = 1
temp = num

while temp:
last_digit = temp % 10
temp = int(temp / 10)
dec_value += last_digit * base
base = base * 8

return dec_value

# Example usage
num = 45621
print(octalToDecimal(num))

Output:

19345
# PROGRAM 15: TO WRITE DATA TO CSV FILE.

import csv

# Fields (headers) for the CSV file


fields = ['Name', 'Branch', 'Year', 'CGPA']

# Rows of data to be written to the CSV file


rows = [
['Nikhil', 'COE', '2', '9.0'],
['Sanchit', 'COE', '2', '9.1'],
['Aditya', 'IT', '2', '9.3'],
['Sagar', 'SE', '1', '9.5'],
['Prateek', 'MCE', '3', '7.8'],
['Sahil', 'EP', '2', '9.1']
]

# Filename where the CSV will be saved


filename = "university_records.csv"

# Writing to the CSV file


with open(filename, 'w', newline='') as csvfile:
csvwriter = csv.writer(csvfile)
csvwriter.writerow(fields) # Write the header
csvwriter.writerows(rows) # Write the data rows

Output:
# PROGRAM 16:-BINARY SEARCH IN AN ARRAY.

def bsearch(ar, item):


beg = 0
last = len(ar) - 1
while beg <= last:
mid = (beg + last) // 2
if item == ar[mid]:
return mid # Element found, return index
elif item > ar[mid]:
beg = mid + 1 # Adjust search to the right half
else:
last = mid - 1 # Adjust search to the left half
return -1 # Return -1 if element is not found

# Get user input for the list and item to search


n = int(input("Enter size of the list: "))
print("Enter elements in ascending order:")
ar = [0] * n # Initialize an empty list of size n

for i in range(n):
ar[i] = int(input(f"Element {i}: ")) # Input elements into the list

item = int(input("Enter element to be searched: ")) # Element to


search
# Perform binary search
ind = bsearch(ar, item)

# Output result
if ind != -1:
print(f"Element found at index {ind}")
else:
print("Element not found!")

Output:

Enter size of the list: 6


Enter elements in ascending order:
Element 0: 1
Element 1: 2
Element 2: 3
Element 3: 4
Element 4: 5
Element 5: 6
Enter element to be searched: 5
Element found at index 4

Enter size of the list: 7


Enter elements in ascending order:
Element 0: 5
Element 1: 6
Element 2: 3
Element 3: 2
Element 4: 4
Element 5: 7
Element 6: 8
Enter element to be searched: 9
Element not found!
# PROGRAM 17:- PROGARM TO READ THE CONTENTS OF
BINARY FILE.

import pickle

# Employee dictionaries
emp1 = {'Empno': 1201, 'Name': 'anushree', 'Age': 25, 'Salary':
47000}
emp2 = {'Empno': 1211, 'Name': 'zoya', 'Age': 30, 'Salary': 48000}
emp3 = {'Empno': 1251, 'Name': 'alex', 'Age': 31, 'Salary': 50000}

# Open the file in write-binary mode and dump employee data


with open('emp.txt', 'wb') as empfile:
pickle.dump(emp1, empfile)
pickle.dump(emp2, empfile)
pickle.dump(emp3, empfile)

# No need to explicitly close the file, as 'with' handles it


automatically
Output:
# PROGRAM 18:- IMPLEMENTATION OF STACK OPERATIONS.

def isempty(stk):
# Check if the stack is empty
if stk == []:
return True
else:
return False

def push(stk, item):


# Push an item to the stack
stk.append(item)

def pop(stk):
# Pop an item from the stack
if isempty(stk):
print("Underflow! Stack is empty.")
else:
item = stk.pop()
return item

def peek(stk):
# Peek at the topmost item of the stack
if isempty(stk):
print("Underflow! Stack is empty.")
else:
return stk[-1]

def display(stk):
# Display the stack
if isempty(stk):
print("Stack Empty")
else:
print("Stack (top -> bottom):")
for item in reversed(stk):
print(item)

stack = []

while True:
print("\nStack Operations")
print("1. Push")
print("2. Pop")
print("3. Peek")
print("4. Display Stack")
print("5. Exit")

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

if ch == 1:
item = int(input("Enter item to push: "))
push(stack, item)
elif ch == 2:
item = pop(stack)
if item is not None:
print("Popped item is:", item)
elif ch == 3:
item = peek(stack)
if item is not None:
print("Topmost item is:", item)
elif ch == 4:
display(stack)
elif ch == 5:
break
else:
print("Invalid choice!")
Output:

Stack Operations
1. Push
2. Pop
3. Peek
4. Display Stack
5. Exit
Enter your choice: 1
Enter item to push: 6

Stack Operations
1. Push
2. Pop
3. Peek
4. Display Stack
5. Exit
Enter your choice: 1
Enter item to push: 2

Stack Operations
1. Push
2. Pop
3. Peek
4. Display Stack
5. Exit
Enter your choice: 1
Enter item to push: 4

Stack Operations
1. Push
2. Pop
3. Peek
4. Display Stack
5. Exit
Enter your choice: 3
Topmost item is: 4

Stack Operations
1. Push
2. Pop
3. Peek
4. Display Stack
5. Exit
Enter your choice: 4
Stack (top -> bottom):
4
2
6
Stack Operations
1. Push
2. Pop
3. Peek
4. Display Stack
5. Exit
Enter your choice: 2
Popped item is: 4

Stack Operations
1. Push
2. Pop
3. Peek
4. Display Stack
5. Exit
Enter your choice: 4
Stack (top -> bottom):
2
6

Stack Operations
1. Push
2. Pop
3. Peek
4. Display Stack
5. Exit
Enter your choice: 5
# PROGRAM 19:- TO MODIFY THE CONTENTS OF BINARY FILE.
def update_binary(word, new):

# Open the file in read-write binary mode


Flag = 0
with open('file.txt', 'r+b') as file:
pos = 0
data = file.read(1)
string = b""

# Reading the file byte by byte


while data:
string += data
if data == b" ":
# Check if the word matches at the position
if string == word:
file.seek(pos)
file.write(new) # Replace the word
Flag = 1
break
else:
string = b"" # Reset the string to start checking the next
word
pos = file.tell()
data = file.read(1)
if Flag:
print("Record successfully updated")
else:
print("Record not found")

# Get the word to be replaced and the new word from user input
word = input("Enter the word to be replaced: ").encode() #
Convert to bytes
new = input("Enter the new word: ").encode() # Convert to bytes

update_binary(word, new)
Output:

Contents of binary file

TEXT FILE
# PROGRAM 20:- PROGRAM TO FIND THE SUM OF
GEOMETRIC PROGRESSION SERIES.

import math

# Input values
a = int(input("Please Enter First Number of a G.P Series: "))
n = int(input("Please Enter the Total Numbers in this G.P Series:
"))
r = int(input("Please Enter the Common Ratio: "))

# Sum formula for G.P.


if r == 1:
total = a * n # If r = 1, the sum is simply a * n
else:
total = (a * (1 - math.pow(r, n))) / (1 - r)

# nth term formula for G.P.


tn = a * (math.pow(r, n - 1))

# Output the results


print("\nThe Sum of Geometric Progression Series = ", total)
print("The tn Term of Geometric Progression Series = ", tn)
Output:
Please Enter First Number of a G.P Series: 1
Please Enter the Total Numbers in this G.P Series: 5
Please Enter the Common Ratio: 2

The Sum of Geometric Progression Series = 31.0


The tn Term of Geometric Progression Series = 16.0
# PROGRAM 21:- TO INTEGRATE MYSQL WITH PYTHON BY
INSERTING RECORDS TO Emp TABLE AND DISPLAY THE
RECORDS.

Output:
SQL OUTPUT
# PROGRAM 22:- TO INTEGRATE MYSQL WITH PYTHON TO
SEARCH AN EMPLOYEE USING EMPID AND DISPLAY THE
RECORD IF PRESENT IN ALREADY EXISTING TABLE EMP, IF
NOT DISPLAY THE APPROPRIATE MESSAGE.

Output:

Python Executed Program Output:


# SQL OUTPUT :
# PROGRAM 23: TO INTEGRATE MYSQL WITH PYTHON TO
SEARCH AN EMPLOYEE USING EMPID AND UPDATE THE
SALARY OF AN EMPLOYEE IF PRESENT IN ALREADY EXISTING
TABLE EMP, IF NOT DISPLAY THE APPROPRIATE MESSAGE.

Output:

Python Executed Program Output:


Sql output:
# PROGRAM 24: INTEGRATE SQL WITH PYTHON BY
IMPORTING THE MYSQL MODULE.

import mysql.connector
con = mysql.connector.connect(host='localhost', user='root',
password='A123456z', db='jinal')
a = con.cursor()
sql = "SELECT * FROM school"
a.execute(sql)
myresult = a.fetchall()
for result in myresult:
print(result)
a.close()
con.close()

Output:

(2, 'ruhani', datetime.date(2002, 12, 23), 'adajan')


(1, 'priya', datetime.date(2002, 2, 2), 'citylight')
(3, 'parineeti', datetime.date(2002, 5, 15), 'vasu')

Create a Database and Table(s) in MySQL and perform the


following:
1. MYSQL QUERY USING ‘AND’
2. MYSQL QUERY USING ‘OR’

3. MYSQL QUERY USING ‘NOT’

4. MYSQL QUERY USING ‘BETWEEN’


5. MYSQL QUERY USING ‘IN’
6. MYSQL QUERY USING ‘LIKE’

7. MYSQL QUERY USING ‘DISTINCT’

8. MYSQL QUERY USING ‘HAVING’


9. MYSQL QUERY USING ‘ORDER BY’

10. MYSQL QUERY USING ‘GROUP BY’


11. MYSQL QUERY USING ‘COUNT’

12. MYSQL QUERY USING ‘MAX’, ‘MIN’, ‘AVG’

You might also like