0% found this document useful (0 votes)
12 views14 pages

MODEL1

Ek do din udh TUC reh rah ek in JJ ahh uhh ahh ahh click shanu da indo um on hai kuch ve ex rtr sr yy da kuchh ni hee ECG ex ek din cc ch

Uploaded by

iamsurya507
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views14 pages

MODEL1

Ek do din udh TUC reh rah ek in JJ ahh uhh ahh ahh click shanu da indo um on hai kuch ve ex rtr sr yy da kuchh ni hee ECG ex ek din cc ch

Uploaded by

iamsurya507
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

PART A

1)How to create numPy array in Python?

To create a NumPy array in Python, you typically import the NumPy library (import numpy as
np) and then use one of the array creation routines, such as np.array() or np.zeros().

2)Why an array should be reshaped? Justify.

Array reshaping is useful when you want to change the dimensions of an existing array without
changing its data. This is often necessary when you're preparing data for mathematical operations or
model training, like converting a 1D array to a 2D array (e.g., for image data in machine learning).
Justification includes ensuring compatibility for operations like matrix multiplication or plotting data in
specific formats.

3)Specify indexing numPy array in Python.

NumPy arrays can be indexed similar to Python lists, using square brackets []. Indexing
starts at 0 for the first element.
For example:

import numpy as np

arr = np.array([1, 2, 3, 4, 5])

# Accessing elements

print(arr[0]) # Output: 1

print(arr[2:4]) # Output: [3, 4]

4) Give the syntax to add elements in to an array using numPy.

You cannot directly add elements to a NumPy array as you would with Python lists. NumPy arrays
have fixed sizes and adding elements would involve creating a new array. Here's how you would append
elements to a NumPy array:

For example:

import numpy as np

arr = np.array([1, 2, 3])

# Appending elements

arr = np.append(arr, [4, 5])

print(arr) # Output: [1 2 3 4 5]
5)When numPy array is preferred over Python list?

NumPy arrays are preferred over Python lists for numerical operations and large datasets due to
their efficiency. They are optimized for numerical operations and use less memory compared to Python
lists.

6)Give the program to activate a Drawing board (Dialog window) of Tkinter

import tkinter as tk

root = tk.Tk()

canvas = tk.Canvas(root, width=400, height=400)

canvas.pack()

# Your drawing operations here

root.mainloop()

7)Specify the syntax to add a Button into Tkinter window (container).

import tkinter as tk

root = tk.Tk()

button = tk.Button(root, text="Click Me")

button.pack()

root.mainloop()

8)Enumerate three geometry managers available in Tkinter.

Three geometry managers in Tkinter are:

1. pack(): Packs widgets in rows or columns.


2. grid(): Organizes widgets in a table-like structure of rows and columns.
3. place(): Places widgets at specific positions relative to their parent widget.

9)Illustrate the three methods related to directions for turtle.

Three methods related to directions in the Turtle module are:

1. turtle.forward(distance): Moves the turtle forward by the specified distance.


2. turtle.left(angle): Turns the turtle counterclockwise by the specified angle.
3. turtle.right(angle): Turns the turtle clockwise by the specified angle.
10) Specify arguments passed inti circle( ) method called in Turtle.

The turtle.circle() method in Turtle takes two main arguments:

 radius: Specifies the radius of the circle to be drawn.


 extent (optional): Specifies the extent of the circle to draw, in degrees. If not provided, a
full circle (360 degrees) is drawn.

PART B (ANY FOUR)

11) Imagine you are developing a program for an online shopping platform where users can create wishlists of
products they intend to purchase. As users browse through products, they can add items to their wishlist, which is
represented as an array. You need to implement a feature that allows users to append new products to the end of their
wishlist array.(5)

Code:

import numpy as np

# Initial wishlist array (empty in this case)

wishlist = np.array([], dtype=str)

# Function to add a new product to the wishlist

def add_to_wishlist(wishlist, product):

wishlist = np.append(wishlist, product)

return wishlist

# Loop to allow user to add products

while True:

product = input("Enter a product to add to your wishlist (or 'done' to finish): ")

if product.lower() == 'done':

break

wishlist = add_to_wishlist(wishlist, product)

# Display the updated wishlist

print("Wishlist:", wishlist)

12) Suppose you are developing a software application for a library management system. The system maintains an
array that lists the books borrowed by a library member in the order they were borrowed. To enhance the user
experience, you decide to display the borrowed books in reverse order, starting from the most recent book borrowed
to the earliest .(5)

CODE:

import numpy as np

# Function to display the borrowed books in reverse order

def display_borrowed_books(borrowed_books):

# Reverse the order of the borrowed books

reversed_books = np.flip(borrowed_books)

return reversed_books

# Example list of borrowed books (in the order they were borrowed)

borrowed_books = np.array(["Book1", "Book2", "Book3", "Book4", "Book5"])

# Display the borrowed books in reverse order

reversed_books = display_borrowed_books(borrowed_books)

print("Borrowed Books in Reverse Order:", reversed_books)

13) Imagine you are working on a project to analyze the performance of two different teams in a series of four matches.
Each team's performance can be represented as a matrix where rows represent different performance metrics (e.g.,
goals scored, shots on target, possession percentage, pass accuracy) and columns represent the four matches played.
You need to calculate the difference in performance metrics between the two teams for each match.(5)

CODE:

import numpy as np

# Define the performance metrics for Team A and Team B

# Rows represent different performance metrics:

# [goals scored, shots on target, possession percentage, pass accuracy]

# Columns represent the four matches played

team_a_performance = np.array([

[2, 1, 3, 4], # goals scored

[5, 3, 6, 7], # shots on target

[55, 48, 60, 65], # possession percentage

[80, 78, 82, 85] # pass accuracy])

team_b_performance = np.array([

[1, 2, 1, 3], # goals scored

[4, 4, 5, 6], # shots on target

[52, 50, 58, 63], # possession percentage


[78, 80, 79, 83] # pass accuracy])

# Calculate the difference in performance metrics between the two teams for each match

performance_difference = team_a_performance - team_b_performance

# Display the result

print("Performance Difference (Team A - Team B):")

print(performance_difference)

14) You are tasked with developing a GUI application for a fitness trainer who needs to track and manage workout
schedules for clients. Design a form using Tkinter that includes widgets for entering client details, selecting workout
types, specifying workout durations, and scheduling sessions.(5)

CODE:

import tkinter as tk

from tkinter import ttk

# Function to handle form submission

def submit_form():

client_name = entry_client_name.get()

workout_type = workout_type_var.get()

workout_duration = entry_workout_duration.get()

schedule_date = entry_schedule_date.get()

# You can add functionality here to save the data or perform other actions

print("Client Name:", client_name)

print("Workout Type:", workout_type)

print("Workout Duration:", workout_duration)

print("Schedule Date:", schedule_date)

# Clear the form after submission

entry_client_name.delete(0, tk.END)

entry_workout_duration.delete(0, tk.END)

entry_schedule_date.delete(0, tk.END)

# Create the main application window

root = tk.Tk()

root.title("Workout Scheduler")
# Create and place labels and entry widgets for client details

label_client_name = tk.Label(root, text="Client Name:")

label_client_name.grid(row=0, column=0, padx=10, pady=10)

entry_client_name = tk.Entry(root)

entry_client_name.grid(row=0, column=1, padx=10, pady=10)

# Create and place labels and dropdown for workout type

label_workout_type = tk.Label(root, text="Workout Type:")

label_workout_type.grid(row=1, column=0, padx=10, pady=10)

workout_type_var = tk.StringVar()

dropdown_workout_type = ttk.Combobox(root, textvariable=workout_type_var)

dropdown_workout_type['values'] = ("Cardio", "Strength", "Flexibility", "Balance")

dropdown_workout_type.grid(row=1, column=1, padx=10, pady=10)

dropdown_workout_type.current(0) # Set default value

# Create and place labels and entry widgets for workout duration

label_workout_duration = tk.Label(root, text="Workout Duration (mins):")

label_workout_duration.grid(row=2, column=0, padx=10, pady=10)

entry_workout_duration = tk.Entry(root)

entry_workout_duration.grid(row=2, column=1, padx=10, pady=10)

# Create and place labels and entry widgets for scheduling date

label_schedule_date = tk.Label(root, text="Schedule Date (YYYY-MM-DD):")

label_schedule_date.grid(row=3, column=0, padx=10, pady=10)

entry_schedule_date = tk.Entry(root)

entry_schedule_date.grid(row=3, column=1, padx=10, pady=10)

# Create and place the submit button

button_submit = tk.Button(root, text="Submit", command=submit_form)

button_submit.grid(row=4, column=0, columnspan=2, pady=20)

# Run the Tkinter event loop

root.mainloop()

15) Write a turtle program to draw a circle in magenta color and fill the circle with orange color.(5)
CODE:

import turtle

# Set up the turtle screen

screen = turtle.Screen()

screen.bgcolor("white")

# Create a turtle object

pen = turtle.Turtle()

# Set the pen color to magenta (outline color)

pen.color("magenta")

# Set the fill color to orange

pen.fillcolor("orange")

# Start filling the shape

pen.begin_fill()

# Draw a circle with a radius of 100 units

pen.circle(100)

# End filling the shape

pen.end_fill()

# Hide the turtle

pen.hideturtle()

# Keep the window open until it is closed by the user

turtle.done()

16) Draw a square inside a circle using Turtle.(5)

CODE:

import turtle

# Set up the turtle screen

screen = turtle.Screen()

screen.bgcolor("white")

# Create a turtle object

pen = turtle.Turtle()

# Draw the circle

pen.penup()
pen.goto(0, -100) # Move to the starting position of the circle

pen.pendown()

pen.circle(100) # Draw the circle with a radius of 100

# Draw the square inside the circle

pen.penup()

pen.goto(-70.71, -70.71) # Move to the bottom-left corner of the square (radius * sqrt(2)/2)

pen.pendown()

pen.setheading(0) # Set the heading to draw the square

for _ in range(4):

pen.forward(141.42) # Length of the side of the square (radius * sqrt(2))

pen.right(90)

# Hide the turtle

pen.hideturtle()

# Keep the window open until it is closed by the user

turtle.done()

PART C (ANY THREE) – 10 marks


17 a. Develop a Python program that prompts the user for two numbers and then performs all basic arithmetic
operations (addition, subtraction, multiplication, division, floor division, and modulo) on them, displaying
the results for each operation.
CODE:
# Function to perform arithmetic operations
def perform_operations(num1, num2):
# Addition
addition = num1 + num2
print(f"Addition: {num1} + {num2} = {addition}")

# Subtraction
subtraction = num1 - num2
print(f"Subtraction: {num1} - {num2} = {subtraction}")

# Multiplication
multiplication = num1 * num2
print(f"Multiplication: {num1} * {num2} = {multiplication}")

# Division
division = num1 / num2
print(f"Division: {num1} / {num2} = {division}")
# Floor Division
floor_division = num1 // num2
print(f"Floor Division: {num1} // {num2} = {floor_division}")

# Modulo
modulo = num1 % num2
print(f"Modulo: {num1} % {num2} = {modulo}")
# Prompt user for two numbers
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
# Perform arithmetic operations
perform_operations(num1, num2)

b. Write a Python program that takes a user's name as input, converts it to uppercase, and then displays
the number of vowels (A, E, I, O, U) present in their name (consider both uppercase and lowercase
vowels).
CODE:
# Function to count vowels in a string
def count_vowels(name):
vowels = "AEIOUaeiou"
vowel_count = 0

for char in name:


if char in vowels:
vowel_count += 1

return vowel_count

# Prompt user for name input


name = input("Enter your name: ")

# Convert name to uppercase


name_upper = name.upper()

# Count vowels in the uppercase name


num_vowels = count_vowels(name_upper)

# Display results
print(f"Uppercase name: {name_upper}")
print(f"Number of vowels in the name: {num_vowels}")
18 a. Create a Python program that defines a recursive function factorial(n) to calculate the factorial of a non-
negative integer n (n!). The factorial of a number is the product of all positive integers less than or equal
to that number.
CODE:
# Recursive function to calculate factorial
def factorial(n):
# Base case: factorial of 0 is 1
if n == 0:
return 1
# Recursive case: factorial of n is n * factorial(n-1)
else:
return n * factorial(n - 1)

# Prompt user for input


n = int(input("Enter a non-negative integer: "))

# Check if the input is non-negative


if n < 0:
print("Factorial is not defined for negative numbers.")
else:
result = factorial(n)
print(f"The factorial of {n} is: {result}")

b. Write a Python function to check whether a number is "Perfect" or not.


Example : The first perfect number is 6, because 1, 2, and 3 are its proper positive divisors, and 1 + 2 +
3 = 6. Equivalently, the number 6 is equal to half the sum of all its positive divisors: ( 1 + 2 + 3 + 6 ) / 2 =
6. The next perfect number is 28 = 1 + 2 + 4 + 7 + 14. This is followed by the perfect numbers 496 and
8128.

CODE:
def is_perfect_number(num):
if num <= 0:
return False

divisors_sum = 0
# Iterate through potential divisors from 1 to num // 2
for i in range(1, num // 2 + 1):
if num % i == 0:
divisors_sum += i

# Check if the sum of divisors equals the original number


return divisors_sum == num

# Prompt user for input


num = int(input("Enter a positive integer to check if it is a Perfect number: "))

# Check if the number is a perfect number


if is_perfect_number(num):
print(f"{num} is a Perfect number.")
else:
print(f"{num} is not a Perfect number.")
19 a Write a Python program that prompts the user for a file name. Use a try-except block to handle the potential
FileNotFoundError exception that might occur if the file doesn't exist. Provide a user-friendly error message
in the except block.
CODE:
# Function to read file content
def read_file(filename):
try:
with open(filename, 'r') as file:
content = file.read()
return content
except FileNotFoundError:
print(f"Error: File '{filename}' not found. Please check the file name and try again.")
return None

# Prompt user for a file name


filename = input("Enter the file name to read: ")

# Attempt to read the file


file_content = read_file(filename)

# Display file content if read successfully


if file_content:
print(f"File content:\n{file_content}")

b You are given a text file named quotes.txt that contains a collection of inspirational quotes. Each quote is on
a new line in the file. Your task is to write a Python program that reads the quotes.txt file line by line and
stores each quote into a list. This list will then be used to display all the quotes in a structured format.
CODE:
# Function to read quotes from file
def read_quotes_from_file(filename):
quotes = []
try:
with open(filename, 'r') as file:
for line in file:
# Remove any leading/trailing whitespace and add to list
quotes.append(line.strip())
except FileNotFoundError:
print(f"Error: File '{filename}' not found.")

return quotes

# File name containing quotes


filename = "quotes.txt"

# Read quotes from file


quotes = read_quotes_from_file(filename)

# Display quotes
if quotes:
print("Inspirational Quotes:")
for idx, quote in enumerate(quotes, start=1):
print(f"{idx}. {quote}")
else:
print("No quotes to display.")
20 a You are a librarian and you have a text file named "books_list.txt" which contains the titles of all the books
available in the library, with each title on a new line. You want to create a Python program that reads this file
line by line and stores each book title into a list. This will allow you to easily manipulate and work with the
book titles in other parts of your application.
CODE:
# Function to read book titles from file
def read_books_list(filename):
books = []
try:
with open(filename, 'r') as file:
for line in file:
# Remove any leading/trailing whitespace and add to list
books.append(line.strip())
except FileNotFoundError:
print(f"Error: File '{filename}' not found.")

return books

# File name containing book titles


filename = "books_list.txt"

# Read book titles from file


book_titles = read_books_list(filename)

# Display book titles


if book_titles:
print("Books Available in the Library:")
for idx, title in enumerate(book_titles, start=1):
print(f"{idx}. {title}")
else:
print("No books available in the library or file not found.")

b Imagine you're working on a grocery store billing system. You have a list of prices for different items
purchased by a customer. You want to write a function to calculate the total bill amount.
CODE:

def calculate_total_bill(prices):

total = sum(prices)

return total

# Example usage:

item_prices = [10.99, 5.49, 7.25, 3.99, 8.50] # Example list of item prices

total_bill = calculate_total_bill(item_prices)

print(f'Total bill amount: ${total_bill:.2f}')

You might also like