Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

upload program from 4a to 9b #18

Merged
merged 1 commit into from
Oct 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 70 additions & 0 deletions pgm4a.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import random

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

merge_sort(left_half) # Recursively sort the left half
merge_sort(right_half) # Recursively sort the right half

# Merge the sorted halves back together
i = j = k = 0
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

# Check for any remaining elements in left_half and right_half
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

return lst

# Insertion Sort Implementation
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key

# Generate a random list of numbers
my_list = [random.randint(0, 999) for _ in range(10)]

# Display the unsorted list
print("Unsorted List:")
print(my_list)

# Sort the list using Insertion Sort
insertion_sort(my_list)
print("\nSorting using Insertion Sort:")
print(my_list)

# Generate another random list of numbers
my_list = [random.randint(0, 999) for _ in range(10)]

# Display the unsorted list
print("\nUnsorted List:")
print(my_list)

# Sort the list using Merge Sort
merge_sort(my_list)
print("\nSorting using Merge Sort:")
print(my_list)

26 changes: 26 additions & 0 deletions pgm4b.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
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
right_val = roman_dict[romanBack[0]]

for numeral in romanBack:
leftVal = roman_dict[numeral]

# Check for subtraction
if leftVal < right_val:
value -= leftVal
else:
value += leftVal

right_val = leftVal

return value


romanStr = input("Enter a Roman Number: ")
print(roman2Dec(romanStr))
52 changes: 52 additions & 0 deletions pgm5a.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import re


# Function to check if a phone number is valid without using Regular Expressions
def isphonenumber(numStr):
# Check if the length is not equal to 12 (e.g., '123-456-7890')
if len(numStr) != 12:
return False

# Iterate through the characters in the phone number
for i in range(len(numStr)):
# Check if the character at index 3 or 7 is not a hyphen
if i == 3 or i == 7:
if numStr[i] != "-":
return False
else:
# Check if all other characters are digits
if not numStr[i].isdigit():
return False

# If all checks pass, the phone number is valid
return True


# Function to check if a phone number is valid using Regular Expressions
def chkphonenumber(numStr):
# Define a Regular Expression pattern for a valid phone number
ph_no_pattern = re.compile(r'^\d{3}-\d{3}-\d{4}$')

# Use the match() function to check if the input matches the pattern
if ph_no_pattern.match(numStr):
return True
else:
return False


# Input: Ask the user to enter a phone number
ph_num = input("Enter a phone number : ")

# Check without Regular Expressions
print("Without using Regular Expression")
if isphonenumber(ph_num):
print("Valid phone number")
else:
print("Invalid phone number")

# Check using Regular Expressions
print("Using Regular Expression")
if chkphonenumber(ph_num):
print("Valid phone number")
else:
print("Invalid phone number")
25 changes: 25 additions & 0 deletions pgm5b.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import re

# Define the regular expression for phone numbers
phone_regex = re.compile(r'\+\d{12}')

# Define the regular expression for email addresses
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
phone_matches = phone_regex.findall(line)

# Print any phone number matches found
for match in phone_matches:
print("Phone Number:", match)

# Search for email addresses in the line
email_matches = email_regex.findall(line)

# Print any email address matches found
for match in email_matches:
print("Email Address:", match)
16 changes: 16 additions & 0 deletions pgm6a.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
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(20):
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")
21 changes: 21 additions & 0 deletions pgm6b.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
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")
50 changes: 50 additions & 0 deletions pgm7a.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
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__()
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):
super().__init__()
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):
super().__init__()
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()
28 changes: 28 additions & 0 deletions pgm7b.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
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()
42 changes: 42 additions & 0 deletions pgm8a.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
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")
45 changes: 45 additions & 0 deletions pgm9a.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
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.')
Loading