PART A

Program 1A:Average Marks

        m1 = int(input("Enter marks for test1 : "))
m2 = int(input("Enter marks for test2 : "))
m3 = int(input("Enter marks for test3 : "))

if m1 <= m2 and m1 <= m3:
avgMarks = (m2+m3)/2
elif m2 <= m1 and m2 <= m3:
avgMarks = (m1+m3)/2
elif m3 <= m1 and m2 <= m2:
avgMarks = (m1+m2)/2

print("Average of best two test marks out of three test’s marks is", avgMarks);
    

Program 1B: Palindrome

       val = int(input("Enter a value : "))
str_val = str(val)
if str_val == str_val[::-1]:
print("Palindrome")
else:
print("Not Palindrome")

for i in range(10):
if str_val.count(str(i)) > 0:
print(str(i),"appears", str_val.count(str(i)), "times");
    

Program 2A:Accept value for N and pass to function

       def fn(n):
if n == 1:
return 0
elif n == 2:
return 1
else:
return fn(n-1) + fn(n-2)

num = int(input("Enter a number : "))
if num > 0:
print("fn(", num, ") = ",fn(num) , sep ="")
else:
print("Error in input")
    

Program 2B: bin2Dec

        def bin2Dec(val):
rev=val[::-1]
dec = 0
i = 0
for dig in rev:
dec += int(dig) * 2**i
i += 1
return dec
def oct2Hex(val):
rev=val[::-1]
dec = 0
i = 0
for dig in rev:
dec += int(dig) * 8**i
i += 1
list=[]
while dec != 0:
list.append(dec%16)
dec = dec // 16
nl=[]
for elem in list[::-1]:
if elem <= 9:
nl.append(str(elem))
else:
nl.append(chr(ord('A') + (elem -10)))
hex = "".join(nl)
return hex
num1 = input("Enter a binary number : ")
print(bin2Dec(num1))
num2 = input("Enter a octal number : ")
print(oct2Hex(num2))
    

Program 3A: Accept a sentence

       s = input("Enter a sentence: ")
w, d, u, l = 0, 0, 0, 0
wordList = s.split()
w = len(wordList)
for c in s:
if c.isdigit():
d = d + 1
elif c.isupper():
u = u + 1
elif c.islower():
l = l + 1

print ("No of Words: ", w)
print ("No of Digits: ", d)
print ("No of Uppercase letters: ", u)
print ("No of Lowercase letters: ", l)
    

Program 3B: find string similarity

       from difflib import SequenceMatcher
a = input("Enter String 1 \n")
b = input("Enter String 2 \n")
print("Similarity between two said strings:")
print(SequenceMatcher(None, a, b).ratio())
    

Program 4A: insertion sort and merge sort

       def merge_sort(lst):
if len(lst) > 1:
mid = len(lst) // 2
left_half = lst[:mid]
right_half = lst[mid:]
merge_sort(left_half)
merge_sort(right_half)

i = j = k = 0 #left arry ind, right arry ind, merge sorted ind
while i < len(left_half) and j < len(right_half):
if left_half[i] < right_half[j]:
lst[k] = left_half[i]
i += 1
else:
lst[k] = right_half[j]
j += 1
k += 1

while i < len(left_half):
lst[k] = left_half[i]
i += 1
k += 1

while j < len(right_half):
lst[k] = right_half[j]
j += 1
k += 1
def insertion_sort(arr):
for i in range(1, len(arr)):
j=i
while arr[j] < arr[j-1] and j>0:
a=arr[j]
arr[j]=arr[j-1]
arr[j-1]=a
j-=1
arr=[2, 6, 5, 1, 3, 4]
insertion_sort(arr)
print("Sorting using Insertion Sort")
print(arr)
lst=[2, 6, 5, 1, 7, 4, 3]
merge_sort(lst)
print("Sorting using Merge Sort")
print(lst)
    

Program 4B:roman2Dec

        def roman2Dec(romStr):
roman_dict ={'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
# Analyze string backwards
romanBack = list(romStr)[::-1]
value = 0
# To keep track of order
rightVal = roman_dict[romanBack[0]]
for numeral in romanBack:
leftVal = roman_dict[numeral]
# Check for subtraction
if leftVal < rightVal:
value -= leftVal
else:
value += leftVal
rightVal = leftVal
return value

romanStr = input("Enter a Roman Number : ")
print(roman2Dec(romanStr))
    

Program 5A: Isphonenumber()

       import re

def isphonenumber(numStr):
if len(numStr) != 12:
return False
for i in range(len(numStr)):
if i==3 or i==7:
if numStr[i] != "-":
return False
else:
if numStr[i].isdigit() == False:
return False
return True

def chkphonenumber(numStr):
ph_no_pattern = re.compile(r'^\d{3}-\d{3}-\d{4}$')
if ph_no_pattern.match(numStr):
return True
else:
return False

ph_num = input("Enter a phone number : ")
print("Without using Regular Expression")
if isphonenumber(ph_num):
print("Valid phone number")
else:
print("Invalid phone number")
print("Using Regular Expression")
if chkphonenumber(ph_num):
print("Valid phone number")
else:
print("Invalid phone number")
    

Program 5B: Search text and phone number

      import re
# Define the regular expression for phone numbers
phone_regex = re.compile(r'\+\d{12}')
email_regex = re.compile(r'[A-Za-z0-9._]+@[A-Za-z0-9]+\.[A-Z|a-z]{2,}')
# Open the file for reading
with open('example.txt', 'r') as f:
# Loop through each line in the file
for line in f:
# Search for phone numbers in the line
matches = phone_regex.findall(line)
# Print any matches found
for match in matches:
print(match)
matches = email_regex.findall(line)
# Print any matches found
for match in matches:
print(match)
    

Program 6A:Accept a file name from the user

       import os.path
import sys
fname = input("Enter the filename : ")
if not os.path.isfile(fname):
print("File", fname, "doesn't exists")
sys.exit(0)
infile = open(fname, "r")
lineList = infile.readlines()
for i in range(6):
print(i+1, ":", lineList[i])
word = input("Enter a word : ")
cnt = 0
for line in lineList:
cnt += line.count(word)
print("The word", word, "appears", cnt, "times in the file")
    

Program 6B: Back Up into Zip file(Backtracking)

        import os
import sys
import pathlib
import zipfile
dirName = input("Enter Directory name that you want to backup : ")
if not os.path.isdir(dirName):
print("Directory", dirName, "doesn't exists")
sys.exit(0)
curDirectory = pathlib.Path(dirName)
with zipfile.ZipFile("MYFIL.zip", mode="w") as archive:
for file_path in curDirectory.rglob("*"):
archive.write(file_path, arcname=file_path.relative_to(curDirectory))
if os.path.isfile("MYFIL.zip"):
print("Archive", "MYFIL.zip", "created successfully")
else:
print("Error in creating zip archive")
    

Program 7A: Area of triangle, circle and rectangle.

       import math
class Shape:
def __init__(self):
self.area = 0
self.name = ""
def showArea(self):
print("The area of the", self.name, "is", self.area, "units")
class Circle(Shape):
def __init__(self,radius):
self.area = 0
self.name = "Circle"
self.radius = radius
def calcArea(self):
self.area = math.pi * self.radius * self.radius
class Rectangle(Shape):
def __init__(self,length,breadth):
self.area = 0
self.name = "Rectangle"
self.length = length
self.breadth = breadth
def calcArea(self):
self.area = self.length * self.breadth
class Triangle(Shape):
def __init__(self,base,height):
self.area = 0
self.name = "Triangle"
self.base = base
self.height = height
def calcArea(self):
self.area = self.base * self.height / 2
c1 = Circle(5)
c1.calcArea()
c1.showArea()
r1 = Rectangle(5, 4)
r1.calcArea()
r1.showArea()
t1 = Triangle(3, 4)
t1.calcArea()
t1.showArea()
    

Program 7B: Empolyee Details

       class Employee:
def __init__(self):
self.name = ""
self.empId = ""
self.dept = ""
self.salary = 0
def getEmpDetails(self):
self.name = input("Enter Employee name : ")
self.empId = input("Enter Employee ID : ")
self.dept = input("Enter Employee Dept : ")
self.salary = int(input("Enter Employee Salary : "))
def showEmpDetails(self):
print("Employee Details")
print("Name : ", self.name)
print("ID : ", self.empId)
print("Dept : ", self.dept)
print("Salary : ", self.salary)
def updtSalary(self):
self.salary = int(input("Enter new Salary : "))
print("Updated Salary", self.salary)

e1 = Employee()
e1.getEmpDetails()
e1.showEmpDetails()
e1.updtSalary()
    

Program 8:Using the concept of polymorphism and inheritance

        class PaliStr:
def __init__(self):
self.isPali = False

def chkPalindrome(self, myStr):
if myStr == myStr[::-1]:
self.isPali = True
else:
self.isPali = False

return self.isPali
class PaliInt(PaliStr):
def __init__(self):
self.isPali = False

def chkPalindrome(self, val):
temp = val
rev = 0
while temp != 0:
dig = temp % 10
rev = (rev*10) + dig
temp = temp //10
if val == rev:
self.isPali = True
else:
self.isPali = False

return self.isPali

st = input("Enter a string : ")
stObj = PaliStr()
if stObj.chkPalindrome(st):
print("Given string is a Palindrome")
else:
print("Given string is not a Palindrome")
val = int(input("Enter a integer : "))
intObj = PaliInt()
if intObj.chkPalindrome(val):
print("Given integer is a Palindrome")
else:
print("Given integer is not a Palindrome")
    

Program 9:Download the all XKCD comics

        import requests
import os
from bs4 import BeautifulSoup

# Set the URL of the first XKCD comic
url = 'https://xkcd.com/1/'

# Create a folder to store the comics
if not os.path.exists('xkcd_comics'):
os.makedirs('xkcd_comics')
# Loop through all the comics
while True:
# Download the page content
res = requests.get(url)
res.raise_for_status()
# Parse the page content using BeautifulSoup
soup = BeautifulSoup(res.text, 'html.parser')
# Find the URL of the comic image
comic_elem = soup.select('#comic img')
if comic_elem == []:
print('Could not find comic image.')
else:
comic_url = 'https:' + comic_elem[0].get('src')

# Download the comic image
print(f'Downloading {comic_url}...')
res = requests.get(comic_url)
res.raise_for_status()
# Save the comic image to the xkcd_comics folder
image_file = open(os.path.join('xkcd_comics', os.path.basename(comic_url)),
'wb')
for chunk in res.iter_content(100000):
image_file.write(chunk)
image_file.close()

# Get the URL of the previous comic
prev_link = soup.select('a[rel="prev"]')[0]
if not prev_link:
break
url = 'https://xkcd.com' + prev_link.get('href')
print('All comics downloaded.')
    

Program 9B:Read the data

        from openpyxl import Workbook
from openpyxl.styles import Font
wb = Workbook()
sheet = wb.active
sheet.title = "Language"
wb.create_sheet(title = "Capital")

lang = ["Kannada", "Telugu", "Tamil"]
state = ["Karnataka", "Telangana", "Tamil Nadu"]
capital = ["Bengaluru", "Hyderabad", "Chennai"]
code =['KA', 'TS', 'TN']

sheet.cell(row = 1, column = 1).value = "State"
sheet.cell(row = 1, column = 2).value = "Language"
sheet.cell(row = 1, column = 3).value = "Code"
ft = Font(bold=True)
for row in sheet["A1:C1"]:
for cell in row:
cell.font = ft

for i in range(2,5):
sheet.cell(row = i, column = 1).value = state[i-2]
sheet.cell(row = i, column = 2).value = lang[i-2]
sheet.cell(row = i, column = 3).value = code[i-2]

wb.save("demo.xlsx")

sheet = wb["Capital"]
sheet.cell(row = 1, column = 1).value = "State"
sheet.cell(row = 1, column = 2).value = "Capital"
sheet.cell(row = 1, column = 3).value = "Code"

ft = Font(bold=True)
for row in sheet["A1:C1"]:
for cell in row:
cell.font = ft

for i in range(2,5):
sheet.cell(row = i, column = 1).value = state[i-2]
sheet.cell(row = i, column = 2).value = capital[i-2]
sheet.cell(row = i, column = 3).value = code[i-2]
wb.save("demo.xlsx")
srchCode = input("Enter state code for finding capital ")
for i in range(2,5):
data = sheet.cell(row = i, column = 3).value
if data == srchCode:
print("Corresponding capital for code", srchCode, "is", sheet.cell(row = i,
column = 2).value)

sheet = wb["Language"]
srchCode = input("Enter state code for finding language ")
for i in range(2,5):
data = sheet.cell(row = i, column = 3).value
if data == srchCode:
print("Corresponding language for code", srchCode, "is", sheet.cell(row = i,
column = 2).value)

wb.close()
    

Program 10A:Combine pages from many PDFs

        from PyPDF2 import PdfWriter, PdfReader
num = int(input("Enter page number you want combine from multiple documents
"))
pdf1 = open('birds.pdf', 'rb')
pdf2 = open('birdspic.pdf', 'rb')
pdf_writer = PdfWriter()
pdf1_reader = PdfReader(pdf1)
page = pdf1_reader.pages[num - 1]
pdf_writer.add_page(page)
pdf2_reader = PdfReader(pdf2)
page = pdf2_reader.pages[num - 1]
pdf_writer.add_page(page)

with open('output.pdf', 'wb') as output:
pdf_writer.write(output)
    

Program 10B: Fetch current weather data

        import json
# Load the JSON data from file
with open('weather_data.json') as f:
data = json.load(f)
# Extract the required weather data
current_temp = data['main']['temp']
humidity = data['main']['humidity']
weather_desc = data['weather'][0]['description']

# Display the weather data
print(f"Current temperature: {current_temp}°C")
print(f"Humidity: {humidity}%")
print(f"Weather description: {weather_desc}")
{
"coord": {
"lon": -73.99,
"lat": 40.73
},
"weather": [
{
"id": 800,
"main": "Clear",
"description": "clear sky",
"icon": "01d"
}
],
"base": "stations",
"main": {
"temp": 15.45,
"feels_like": 12.74,
"temp_min": 14.44,
"temp_max": 16.11,
"pressure": 1017,
"humidity": 64
},
"visibility": 10000,
"wind": {
"speed": 4.63,
"deg": 180
},
"clouds": {
"all": 1
},
"dt": 1617979985,
"sys": {
"type": 1,
"id": 5141,
"country": "US",
"sunrise": 1617951158,
"sunset": 1618000213
},
"timezone": -14400,
"id": 5128581,
"name": "New York",
"cod": 200
}
    

PART B

Program 1:Pattern

      def run():
j = 7
k = 7
p = 1
for i in range(8):
print (" " * k," #" * i)
k -=1
while j > 1:
j -= 1
print (" " * p," #" * j)
p +=1
run()  
    

Program 2:Read Name and Year

       name=input('Enter the name of the person: ')
yob=int(input('Enter the year of birth of the person: '))
age=2022-yob
if age>59:
print(name,'is a senior citizen')
else:
print(name,'is not a sinior citizen') 
    

Program 3:Birthday Info

        birthdays = {'Alika': 'Apr 1', 'Malika': 'Dec 12',
'Rolika': 'Mar 4'}
while True:
print('Enter a name: (Press Enter to quit)')
name = input()
if name == '':
break
if name in birthdays:
print(birthdays[name] + ' is the birthday of ' + name)
else:
print('I do not have birthday information for ' + name)
print('What is their birthday?')
bday = input()
birthdays[name] = bday
print('Birthday database updated.')
    

Program 4:Bike Name and Features

        # define a class
class Bike:
name = ""
gear = 0
# create object of class
bike1 = Bike()
# access attributes and assign new values
bike1.gear = 5
bike1.name = "Yamaha FZ"
print(f"Name: {bike1.name}, Gears: {bike1.gear} ")
    

Program 5:Tictoktoy Board

        theBoard = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ', 'mid-L': ' ', 'mid-M': ' ', 'mid-R': ' ', 'low-L': ' ', 'low-
M': ' ', 'low-R': ' '}

def printBoard(board):
print(board['top-L'] + '|' + board['top-M'] + '|' + board['top-R'])
print('-+-+-')
print(board['mid-L'] + '|' + board['mid-M'] + '|' + board['mid-R'])
print('-+-+-')
print(board['low-L'] + '|' + board['low-M'] + '|' + board['low-R'])
turn = 'X'
for i in range(9):
printBoard(theBoard)
print('Turn for ' + turn + '. Move on which space?')
move = input()
theBoard[move] = turn
if turn == 'X':
turn = 'O'
else:
turn = 'X'
printBoard(theBoard)