MODEL1
MODEL1
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().
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.
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
# Accessing elements
print(arr[0]) # Output: 1
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
# Appending elements
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.
import tkinter as tk
root = tk.Tk()
canvas.pack()
root.mainloop()
import tkinter as tk
root = tk.Tk()
button.pack()
root.mainloop()
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
return wishlist
while True:
product = input("Enter a product to add to your wishlist (or 'done' to finish): ")
if product.lower() == 'done':
break
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
def display_borrowed_books(borrowed_books):
reversed_books = np.flip(borrowed_books)
return reversed_books
# Example list of borrowed books (in the order they were borrowed)
reversed_books = display_borrowed_books(borrowed_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
team_a_performance = np.array([
team_b_performance = np.array([
# Calculate the difference in performance metrics between the two teams for each match
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
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
entry_client_name.delete(0, tk.END)
entry_workout_duration.delete(0, tk.END)
entry_schedule_date.delete(0, tk.END)
root = tk.Tk()
root.title("Workout Scheduler")
# Create and place labels and entry widgets for client details
entry_client_name = tk.Entry(root)
workout_type_var = tk.StringVar()
# Create and place labels and entry widgets for workout duration
entry_workout_duration = tk.Entry(root)
# Create and place labels and entry widgets for scheduling date
entry_schedule_date = tk.Entry(root)
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
screen = turtle.Screen()
screen.bgcolor("white")
pen = turtle.Turtle()
pen.color("magenta")
pen.fillcolor("orange")
pen.begin_fill()
pen.circle(100)
pen.end_fill()
pen.hideturtle()
turtle.done()
CODE:
import turtle
screen = turtle.Screen()
screen.bgcolor("white")
pen = turtle.Turtle()
pen.penup()
pen.goto(0, -100) # Move to the starting position of the circle
pen.pendown()
pen.penup()
pen.goto(-70.71, -70.71) # Move to the bottom-left corner of the square (radius * sqrt(2)/2)
pen.pendown()
for _ in range(4):
pen.right(90)
pen.hideturtle()
turtle.done()
# 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
return vowel_count
# 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)
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
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
# 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
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)