PROGRAMS FROM 26 -36
26. Write a function called
draw_point that takes a Canvas and a Point as arguments and draws a
representation of the Point on the Canvas.
class
Canvas:
def __init__(self, width, height):
self.width = width
self.height = height
def draw(self, shape, color):
# Function to draw shape on the canvas
with given color
print(f"Drawing {shape} with color
{color}")
class
Point:
def __init__(self, x, y):
self.x = x
self.y = y
def
draw_point(canvas, point):
"""
Draw a point on the canvas.
Args:
canvas (Canvas): Canvas object to draw
on
point (Point): Point object to draw
"""
point_color = 'black' # Example: Setting point color to black
point_size = 1 # Example: Setting point size to 1 pixel
canvas.draw(point, point_color) # Draw the point
#
Example usage
canvas
= Canvas(500, 500)
point
= Point(10, 20)
draw_point(canvas,
point)
27. Define a new class called
Circle with appropriate attributes and instantiate a few Circle objects. Write
a function called draw_circle that draws circles on the canvas.
class
Canvas:
def
__init__(self, width, height):
self.width
= width
self.height
= height
def
draw(self, shape, color):
#
Function to draw shape on the canvas with given color
pass
class
Circle:
def
__init__(self, x, y, radius, color):
self.x
= x
self.y
= y
self.radius
= radius
self.color
= color
def
draw_circle(canvas, circle):
"""
Draw
a circle on the canvas with the given color.
Args:
canvas
(Canvas): Canvas object to draw on
circle
(Circle): Circle object to draw
"""
#
Assuming the Canvas class has a draw method that takes a shape and a color as
arguments,
#
you can implement the logic to draw the circle on the Canvas object using the
x, y, and radius
#
attributes of the Circle object as parameters.
#
You can also use the color attribute of the Circle object to specify the fill
color of the circle.
circle_color
= circle.color # Get the color of the
circle
circle_center
= (circle.x, circle.y) # Get the center
coordinates of the circle
circle_radius
= circle.radius # Get the radius of the
circle
canvas.draw(circle_center,
circle_radius, circle_color) # Draw the
circle on the canvas with the specified color
28. Write a python code to read a
phone number and email-id from the user and validate it for correctness.
import
re
def
validate_phone(phone):
# Validates 10-digit phone numbers (can
adjust for country codes if needed)
pattern = r"^[6-9]\d{9}$"
return re.match(pattern, phone)
def
validate_email(email):
# Basic email validation pattern
pattern =
r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
return re.match(pattern, email)
#
Input from user
phone
= input("Enter phone number: ")
email
= input("Enter email ID: ")
#
Validation
if
validate_phone(phone):
print("Valid phone number")
else:
print("Invalid phone number")
if
validate_email(email):
print("Valid email ID")
else:
print("Invalid email ID")
Output:
Enter
phone number: 9876543210
Enter
email ID: user123@gmail.com
Valid
phone number
Valid
email ID
29. Write a Python code to merge
two given file contents into a third file.
#
Function to merge two files into a third file
def
merge_files(file1, file2, merged_file):
try:
# Open first file in read mode
with open(file1, 'r') as f1:
# Read contents of first file
file1_contents = f1.read()
# Open second file in read mode
with open(file2, 'r') as f2:
# Read contents of second file
file2_contents = f2.read()
# Open third file in write mode
with open(merged_file, 'w') as mf:
# Write merged contents to third
file
mf.write(file1_contents)
mf.write(file2_contents)
print(f"Contents of '{file1}' and
'{file2}' merged successfully into '{merged_file}'.")
except Exception as e:
print("An error occurred:",
e)
#
File paths for the files to be merged and the merged file
file1
= "file1.txt"
file2
= "file2.txt"
merged_file
= "merged_file.txt"
#
Call the merge_files function
merge_files(file1,
file2, merged_file)
Output:
Contents
of 'file1.txt' and 'file2.txt' merged successfully into 'merged_file.txt'.
30.
Write a Python code to open a given file and construct a function to check for
given words present in it and display on found.
#
Function to check for given words in a file and display if found
def
check_for_words(file_path, words):
try:
# Open file in read mode
with open(file_path, 'r') as file:
# Read contents of file
file_contents = file.read()
# Loop through each word in the given
list
for word in words:
# Check if word is present in file
contents
if word in file_contents:
print(f"Word '{word}'
found in '{file_path}'")
else:
print(f"Word '{word}' not
found in '{file_path}'")
except Exception as e:
print("An error occurred:", e)
#
File path for the file to be checked
file_path
= "file.txt"
#
List of words to be checked in the file
words_to_check
= ["apple", "banana", "cherry"]
#
Call the check_for_words function
check_for_words(file_path,
words_to_check)
Output:
Word 'apple'
found in 'file.txt'
Word 'banana'
not found in 'file.txt'
Word 'cherry'
found in 'file.txt'
31. Write a Python code to Read
text from a text file, find the word with most number of occurrences
#
Function to find the word with most occurrences in a text file
def
find_most_frequent_word(file_path):
try:
# Open file in read mode
with open(file_path, 'r') as file:
# Read contents of file
file_contents = file.read()
# Split the file contents into words
words = file_contents.split()
# Create a dictionary to store word
frequencies
word_freq = {}
# Loop through each word and count its
occurrences
for word in words:
if word in word_freq:
word_freq[word] += 1
else:
word_freq[word] = 1
# Find the word with the most
occurrences
most_frequent_word = max(word_freq,
key=word_freq.get)
# Return the most frequent word and its
frequency
return most_frequent_word,
word_freq[most_frequent_word]
except Exception as e:
print("An error occurred:",
e)
return None, 0
#
File path for the text file to be read
file_path
= "file.txt"
#
Call the find_most_frequent_word function
most_frequent_word,
frequency = find_most_frequent_word(file_path)
#
Print the most frequent word and its frequency
if
most_frequent_word:
print(f"The most frequent word is
'{most_frequent_word}' with a frequency of {frequency} times.")
Output:
The
most frequent word is 'apple' with a frequency of 3 times.
32. Write a function that reads a
file file1and displays the number of words, number of vowels, blank spaces,
lower case letters and uppercase letters.
#
Function to count vowels, blank spaces, lower case letters, and uppercase
letters in a text file
def
count_chars(file_path):
try:
# Open file in read mode
with open(file_path, 'r') as file:
# Read contents of file
file_contents = file.read()
# Initialize counters
num_vowels = 0
num_blank_spaces = 0
num_lower_case = 0
num_upper_case = 0
# Loop through each character in the
file contents
for char in file_contents:
if char.isalpha():
# Check for vowels
if char.lower() in ['a', 'e',
'i', 'o', 'u']:
num_vowels += 1
# Check for lowercase letters
if char.islower():
num_lower_case += 1
# Check for uppercase letters
if char.isupper():
num_upper_case += 1
elif char.isspace():
# Count blank spaces
num_blank_spaces += 1
# Return the counts
return num_vowels, num_blank_spaces,
num_lower_case, num_upper_case
except Exception as e:
print("An error occurred:",
e)
return 0, 0, 0, 0
#
File path for the text file to be read
file_path
= "file.txt"
#
Call the count_chars function
num_vowels,
num_blank_spaces, num_lower_case, num_upper_case = count_chars(file_path)
#
Print the counts
print(f"Number
of vowels: {num_vowels}")
print(f"Number
of blank spaces: {num_blank_spaces}")
print(f"Number
of lower case letters: {num_lower_case}")
print(f"Number
of upper case letters: {num_upper_case}")
Output:
Number
of vowels: 3
Number
of blank spaces: 1
Number
of lower case letters: 8
Number
of upper case letters: 2
33. Import numpy, Plotpy and Scipy
and explore their functionalities.
1 NumPy (Numerical Python): NumPy
provides support for arrays, matrices, and mathematical operations on them.
Some of the key functionalities of NumPy include:
• Creating arrays and matrices of
different dimensions
• Performing element-wise mathematical
operations on arrays
• Performing linear algebra operations
such as matrix multiplication, inverse, etc.
• Performing statistical operations on
arrays
• Random number generation
• Data reshaping, slicing, and indexing
• Mathematical functions for basic
arithmetic, trigonometry, logarithms, etc.
2 Matplotlib (Plotting Library):
Matplotlib is a popular data visualization library in Python that provides a
wide range of options for creating various types of plots and charts. Some of
the key functionalities of Matplotlib include:
• Creating line plots, scatter plots,
bar plots, histograms, etc.
• Customizing plot appearance such as
labels, titles, colors, etc.
• Adding annotations, legends, and gridlines
to plots
• Saving plots in various formats such
as PNG, JPEG, PDF, etc.
• Plotting multiple plots in a single
figure
• Creating 3D plots for visualization
of 3D data
3 SciPy (Scientific Python): SciPy is a
library built on top of NumPy that provides additional functionality for
scientific computing, including:
• Integration and optimization
techniques
• Signal processing and image
processing
• Interpolation and curve fitting
• Statistics and probability
distributions
• Sparse matrix operations
• Numerical integration and solving
ordinary differential equations (ODEs)
• Linear programming and optimization
algorithms
• Fourier analysis and signal
processing
• Statistical tests and hypothesis
testing
These
are just some of the functionalities of NumPy, Matplotlib, and SciPy. These
libraries are widely used in various domains such as data science, machine
learning, physics, engineering, and finance, among others, due to their
extensive capabilities for numerical computing, data analysis, and visualization.
34. Install NumPypackage with pip
and explore it.
Step
1: Install NumPy using pip Open a command prompt or terminal on your computer
and run the following command to install NumPy:
pip
install numpy
This
will download and install the NumPy package in your Python environment.
Step
2: Import NumPy in Python Once NumPy is installed, you can import it in your
Python script or Jupyter notebook using the import statement:
import
numpy as np
Here,
np is an alias commonly used for NumPy to make it easier to refer to its
functions and objects in the code.
Step
3: Explore NumPy functionalities After importing NumPy, you can start exploring
its functionalities. Some of the common functionalities of NumPy include:
• Creating arrays and matrices using
the numpy.array(), numpy.zeros(), numpy.ones(), numpy.arange(), numpy.random
functions, etc.
• Performing mathematical operations on
arrays such as addition, subtraction, multiplication, division, etc.
• Performing element-wise operations on
arrays using NumPy's built-in functions for mathematical operations such as
numpy.sin(), numpy.cos(), numpy.exp(), etc.
• Performing linear algebra operations
such as matrix multiplication, matrix inversion, etc. using the functions in
the numpy.linalg module.
• Performing statistical operations on
arrays using functions such as numpy.mean(), numpy.median(), numpy.std(), etc.
• Reshaping, slicing, and indexing
arrays using NumPy's built-in functions for array manipulation such as
numpy.reshape(), numpy.slice(), and array indexing using square brackets ([ ]).
•Generating
random numbers using NumPy's numpy.random module, which provides functions for
generating random numbers from various probability distributions.
35. Write a program to implement
Digital Logic Gates – AND, OR, NOT, EX-OR
def
AND_gate(a, b):
return a and b
def
OR_gate(a, b):
return a or b
def
NOT_gate(a):
return not a
def
XOR_gate(a, b):
return a ^ b
#
Example usage
a
= True
b
= False
print("AND
gate:")
print(f"{a}
AND {b} = {AND_gate(a, b)}")
print("\nOR
gate:")
print(f"{a}
OR {b} = {OR_gate(a, b)}")
print("\nNOT
gate:")
print(f"NOT
{a} = {NOT_gate(a)}")
print("\nXOR
gate:")
print(f"{a}
XOR {b} = {XOR_gate(a, b)}")
Output:
AND
gate:
True
AND False = False
OR
gate:
True
OR False = True
NOT
gate:
NOT
True = False
XOR
gate:
True
XOR False = True
36. Write a GUI program to create a window
wizard having two text labels, two text fields and two buttons as Submit and
Reset
import tkinter as tk
def submit():
# Get input from text fields and perform submit operation
name = name_entry.get()
age = age_entry.get()
print(f"Name: {name}, Age: {age}")
def reset():
# Clear input fields
name_entry.delete(0, tk.END)
age_entry.delete(0, tk.END)
# Create main window
window = tk.Tk()
window.title("Window Wizard")
# Create text labels
name_label = tk.Label(window,
text="Name:")
age_label = tk.Label(window,
text="Age:")
# Create text fields
name_entry = tk.Entry(window)
age_entry = tk.Entry(window)
# Create buttons
submit_button = tk.Button(window,
text="Submit", command=submit)
reset_button = tk.Button(window,
text="Reset", command=reset)
# Place text labels, text fields, and
buttons in the window
name_label.grid(row=0, column=0,
padx=10, pady=10)
name_entry.grid(row=0, column=1, padx=10,
pady=10)
age_label.grid(row=1, column=0, padx=10,
pady=10)
age_entry.grid(row=1, column=1, padx=10,
pady=10)
submit_button.grid(row=2, column=0,
padx=10, pady=10)
reset_button.grid(row=2, column=1,
padx=10, pady=10)
# Start main event loop
window.mainloop()
Beyond Syllabus Programs:
Python program for removing i-th
character from a string
Different methods for removing the i-th character (a) Using String Slicing (b) Using a
for Loop
(c) Using join() with List Comprehension
(a)
s = "PythonProgramming"
# Index of the character to remove
i = 6
# Removing i-th character
res = s[:i] + s[i+1:]
print(res)
Output: Pythonrogramming
(b)
s = "PythonProgramming"
# Index of character to remove
i = 6
# Initialize an empty string to store result
res = ''
# Loop through each character in original string
for j in range(len(s)):
# Check if current index is not index to remove
if j != i:
# Add current character to result string
res += s[j]
print(res)
output: Pythonrogramming
(c)
s = "PythonProgramming"
# Index of the character to remove
i = 6
# Removing i-th character using list comprehension
res = ''.join([s[j] for j in range(len(s)) if j != i])
print(res)
Output: Pythonrogramming
2. Python program to repeat M characters of a string N times
def repeat(word, m, n):
# if number of characters greater than length of word.
# set number of characters = length of word
if(m > len(word)):
m = len(word)
repeat_word = word[:m]
result = ""
for i in range(n):
result = result+repeat_word
print(result)
# driver code
repeat("geeks", 2, 3)
Output: gegege
Comments