tower of Hanoi # Recursive Python function to solve the tower of hanoi def TowerOfHanoi(n , source, destination, auxiliary): if n==1: print ("Move disk 1 from source",source,"to destination",destination) return TowerOfHanoi(n-1, source, auxiliary, destination) print ("Move disk",n,"from source",source,"to destination",destination) TowerOfHanoi(n-1, auxiliary, destination, source) # Driver code n = 4 TowerOfHanoi(n,'A','B','C') # A, C, B are the name of rods PROGRAM:2 Python Program to Count Vowels in a String str1 = input("Please Enter Your Own String : ") vowels = 0 for i in str1: if (ord(i) == 65 or ord(i) == 69 or ord(i) == 73 or ord(i) == 79 or ord(i) == 85 or ord(i) == 97 or ord(i) == 101 or ord(i) == 105 or ord(i) == 111 or ord(i) == 117): vowels = vowels + 1 print("Total Number of Vowels in this String =", vowels) PROGRAM:3 Python program prints the right pascals triangle pattern of mirrored numbers using a while loop. rows = int(input("Enter Right Pascals Mirrored Numbers Rows = ")) print("====Right Pascals Mirrored Numbers Triangle Pattern====") i = rows while i >= 1: j = i while j <= rows: print(j, end=' ') j = j + 1 k = rows - 1 while k >= i: print(k, end=' ') k = k - 1 print() i = i - 1 i = 2 while i <= rows: j = i while j <= rows: print(j, end=' ') j = j + 1 k = rows - 1 while k >= i: print(k, end=' ') k = k - 1 print() i = i + 1 6A import os.path import sys fname = input('Enter the filename: ') if not os.path.isfile(fname): print("File", fname, "doesn't exist") sys.exit(0) infile = open(fname, "r") linelist = infile.readlines() for i in range(20): # This will only display the first 20 lines, regardless of the user input print(i + 1, ":", linelist[i]) word = input("Enter a word: ") cnt = 0 # There's no need to loop through the lines twice; you can count the word frequency in the same loop. for line in linelist: cnt += line.count(word) print("The word", word, "appears", cnt, "times in the file") 6B 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 exist") sys.exit(0) curdirectory = pathlib.Path(dirName) with zipfile.ZipFile("myZip.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("myZip.zip"): print("Archive 'myZip.zip' created successfully") else: print("Error in creating zip archive") 7A 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): super().__init__() # Call the constructor of the parent class. self.name = "circle" self.radius = radius def calarea(self): self.area = math.pi * self.radius * self.radius class Rectangle(Shape): def __init__(self, length, breadth): super().__init__() # Call the constructor of the parent class. self.name = "Rectangle" self.length = length self.breadth = breadth def calarea(self): self.area = self.length * self.breadth class Triangle(Shape): def __init__(self, base, height): super().__init__() # Call the constructor of the parent class. self.name = "Triangle" self.base = base self.height = height def calarea(self): self.area = (self.base * self.height) / 2 c1 = Circle(5) c1.calarea() c1.showArea() r1 = Rectangle(4, 5) r1.calarea() r1.showArea() t1 = Triangle(3, 4) t1.calarea() t1.showArea() 7B 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() 8 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 an integer : ")) intObj = PaliInt() if intObj.chkPalindrome(val): print("Given integer is a Palindrome") else: print("Given integer is not a Palindrome") 9A 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.') 9B 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() 10A 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) 10B 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}")