KEMBAR78
Python | PDF | Mean Squared Error | Applied Mathematics
0% found this document useful (0 votes)
14 views14 pages

Python

The document contains various Python code snippets demonstrating data visualization using Matplotlib, basic string manipulations, game development with Pygame, and performance metrics calculations using Scikit-learn. It includes examples of generating different types of graphs, implementing a Pong game, and calculating classification metrics like accuracy and precision. The code is structured in segments, each focusing on a specific functionality or concept.

Uploaded by

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

Python

The document contains various Python code snippets demonstrating data visualization using Matplotlib, basic string manipulations, game development with Pygame, and performance metrics calculations using Scikit-learn. It includes examples of generating different types of graphs, implementing a Pong game, and calculating classification metrics like accuracy and precision. The code is structured in segments, each focusing on a specific functionality or concept.

Uploaded by

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

test

import pandas as pd
import matplotlib.pyplot as plt

df=pd.read_csv(r'C:\Users\ADMIN\Downloads\students.csv')
df.columns = [column.replace(" ", "_") for column in df.columns]

df.query('marks >= 80',inplace=True)


a=df.plot(x="name",y="marks",kind="bar",color="salmon",title="student marks")
a.set_xlabel('Name')
a.set_ylabel('marks')
plt.legend()
plt.show()

string1

rows=5
for i in range(rows,0,-1):
for j in range(1,rows):
print(i, end=" ")
print()
rows=5
for i in range(rows+1,1,-1):
for j in range(i-1,rows+1):
print(j, end=" ")
print()

practice1

sentence = "Learning Python is exciting and rewarding"


print(sentence.upper())
print(sentence.lower())
print(sentence.split())
print(sentence.find("exciting"))
print(sentence.replace("Python", "Java"))
print(sentence.title())
print(sentence.count("e"))
print(sentence.startswith("Learning"))
print(sentence.endswith("rewarding"))
print(sentence.swapcase())
print(sentence.isalpha())
print(len(sentence))

rishab

# Aim: To visualize different types of data using matplotlib, including line


graphs, bar graphs, histograms, scatter plots, and pie charts.

import matplotlib.pyplot as plt


import numpy as np
print("""enter 1.line graph
2.bar graph
3.histogram
4.scatter plot
5.pie chart""")
graph=int(input("how do you want to visualize data :"))

if graph == 1 :
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.figure()
plt.plot(x, y, label='sin(x)', color='teal')
plt.title("Line Graph")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.legend()
plt.grid()

if graph == 2 :
categories = ['A', 'B', 'C', 'D', 'E']
values = [5, 7, 3, 8, 4]
plt.figure()
plt.bar(categories, values, color='cyan')
plt.title("Bar Graph")
plt.xlabel("Categories")
plt.ylabel("Values")

if graph == 3 :
data = np.random.randn(1000)
plt.figure()
plt.hist(data, bins=30, color='crimson', alpha=0.7)
plt.title("Histogram")
plt.xlabel("Value")
plt.ylabel("Frequency")

if graph == 4 :
x = np.random.rand(50)
y = np.random.rand(50)
sizes = np.random.rand(50) * 300
colors = np.random.rand(50)
plt.figure()
plt.scatter(x, y, s=sizes, c=colors, cmap='plasma', alpha=0.75)
plt.colorbar(label="Color Scale")
plt.title("Scatter Plot")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")

if graph == 5 :
labels = ['Apple', 'Banana', 'Cherry', 'Date']
sizes = [20, 30, 35, 15]
colors = ['red', 'yellow', 'pink', 'brown']
plt.figure()
plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=140)
plt.title("Pie Chart")
plt.show()

eko

from sklearn.metrics import mean_squared_error, precision_score, recall_score,


f1_score, accuracy_score
import numpy as np

# Sample Actual vs Predicted values (for MSE & RMSE)


y_actual = np.array([3, -0.5, 2, 7])
y_predicted = np.array([2.5, 0.0, 2, 8])

# Calculate MSE & RMSE


mse = mean_squared_error(y_actual, y_predicted)
rmse = np.sqrt(mse)

print("Mean Squared Error (MSE):", mse)


print("Root Mean Squared Error (RMSE):", rmse)

# Sample Confusion Matrix values


y_true = np.array([1, 0, 1, 1, 0, 1, 0, 1, 1, 0]) # Actual labels
y_pred = np.array([1, 0, 1, 0, 0, 1, 0, 1, 0, 0]) # Predicted labels
print(y_true)
print(y_pred)
# Calculate Classification Metrics
accuracy = accuracy_score(y_true, y_pred)
precision = precision_score(y_true, y_pred)
recall = recall_score(y_true, y_pred)
f1 = f1_score(y_true, y_pred)

print("Accuracy:", accuracy)
print("Precision:", precision)
print("Recall:", recall)
print("F1 Score:", f1)

biggest

def max():
if n1>n2 and n1>n3:
print(n1,"is the greatest")
elif n2>n1 and n2>n3:
print(n2,"is the greatest")
elif n3>n2 and n3>n1:
print(n3,"is the greatest")

n1=int(input("Enter the 1st number:"))


n2=int(input("Enter the 2nd number:"))
n3=int(input("Enter the 3rd number:"))
max()

plot

import matplotlib.pyplot as plt


import numpy as np

def plot_graph(choice):
np.random.seed(0)

if choice == 1: # Line Graph


x = np.linspace(0, 10, 100)
plt.plot(x, np.sin(x), label='sin(x)', color='teal')
plt.xlabel("X-axis"), plt.ylabel("Y-axis"), plt.legend()

elif choice == 2: # Bar Graph


plt.bar(['A', 'B', 'C', 'D', 'E'], [5, 7, 3, 8, 4], color='cyan')

elif choice == 3: # Histogram


plt.hist(np.random.randn(1000), bins=30, color='crimson', alpha=0.7)
plt.xlabel("Value"), plt.ylabel("Frequency")

elif choice == 4: # Scatter Plot


x, y, sizes, colors = np.random.rand(4, 50)
plt.scatter(x, y, s=sizes * 300, c=colors, cmap='plasma', alpha=0.75)
plt.colorbar(label="Color Scale"), plt.xlabel("X-axis"), plt.ylabel("Y-
axis")

elif choice == 5: # Pie Chart


plt.pie([20, 30, 35, 15], labels=['Apple', 'Banana', 'Cherry', 'Date'],
colors=['red', 'yellow', 'pink', 'brown'], autopct='%1.1f%%',
startangle=140)
else:
print("Invalid choice! Please enter a number between 1 and 5.")
return

plt.title(["Line Graph", "Bar Graph", "Histogram", "Scatter Plot", "Pie Chart"]


[choice-1])
plt.show()

print("1.Line 2.Bar 3.Histogram 4.Scatter 5.Pie")


try:
plot_graph(int(input("Choose a graph (1-5): ")))
except ValueError:
print("Invalid input! Enter a number.")

matplot

import numpy as np
import matplotlib.pyplot as plt

data_x = np.array([2,4,8,6,8,10,14,12,16,20])
data_y = np.array([3,5,7,8,9,6,7,5,9,8])

mean_x=np.mean(data_x)
mean_y=np.mean(data_y)
std_x=np.std(data_x)
std_y=np.std(data_y)

cov=np.sum((data_x-mean_x)*(data_y-mean_y))/(len(data_x)-1)
slope=cov/(std_x**2)

intercept=mean_y-slope*mean_x

y_pred=slope*data_x+intercept

plt.scatter(data_x,data_y)
plt.plot(data_x,y_pred,color='blue')

plt.xlabel('X values')
plt.ylabel('Y values')
plt.title('Simple Linear Regression')
plt.show()
print("the slope of the regression line is:{:.2f}".format(intercept))

scikitlearn

from sklearn.metrics import mean_squared_error, precision_score, recall_score,


f1_score, accuracy_score
import numpy as np

# Sample Actual vs Predicted values (for MSE & RMSE)


y_actual = np.array([3, -0.5, 2, 7])
y_predicted = np.array([2.5, 0.0, 2, 8])

# Calculate MSE & RMSE


mse = mean_squared_error(y_actual, y_predicted)
rmse = np.sqrt(mse)

print("Mean Squared Error (MSE):", mse)


print("Root Mean Squared Error (RMSE):", rmse)

# Sample Confusion Matrix values


y_true = np.array([1, 0, 1, 1, 0, 1, 0, 1, 1, 0]) # Actual labels
y_pred = np.array([1, 0, 1, 0, 0, 1, 0, 1, 0, 0]) # Predicted labels

# Calculate Classification Metrics


accuracy = accuracy_score(y_true, y_pred)
precision = precision_score(y_true, y_pred)
recall = recall_score(y_true, y_pred)
f1 = f1_score(y_true, y_pred)

print("Accuracy:", accuracy)
print("Precision:", precision)
print("Recall:", recall)
print("F1 Score:", f1)

+-0

import pygame

# Initialize pygame
pygame.init()

# Screen dimensions
WIDTH, HEIGHT = 800, 600
BALL_SPEED = 5
PADDLE_SPEED = 8
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)

# Create the screen


screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Single-Paddle Pong 🏓")

# Paddle and Ball


paddle_width, paddle_height = 2500, 10
ball_size = 15

# Paddle (at bottom)


paddle = pygame.Rect(WIDTH//2 - paddle_width//2, HEIGHT - 40, paddle_width,
paddle_height)

# Ball (center start)


ball = pygame.Rect(WIDTH//2 - ball_size//2, HEIGHT//2 - ball_size//2, ball_size,
ball_size)
ball_dx, ball_dy = BALL_SPEED, -BALL_SPEED

# Score
score = 0
font = pygame.font.Font(None, 50)
# Game loop
running = True
while running:
pygame.time.delay(20) # Control speed
screen.fill(BLACK)

# Event handling
keys = pygame.key.get_pressed()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False

# Move paddle (left/right)


if keys[pygame.K_LEFT] and paddle.left > 0:
paddle.x -= PADDLE_SPEED
if keys[pygame.K_RIGHT] and paddle.right < WIDTH:
paddle.x += PADDLE_SPEED

# Move ball
ball.x += ball_dx
ball.y += ball_dy

# Ball collision with walls


if ball.left <= 0 or ball.right >= WIDTH:
ball_dx = -ball_dx
if ball.top <= 0:
ball_dy = -ball_dy

# Ball collision with paddle


if ball.colliderect(paddle):
ball_dy = -ball_dy
score += 1 # Increase score when ball hits paddle

# Game Over (ball falls below paddle)


if ball.bottom >= HEIGHT:
running = False

# Draw paddle, ball, and score


pygame.draw.rect(screen, WHITE, paddle)
pygame.draw.ellipse(screen, WHITE, ball)

score_text = font.render(f"Score: {score}", True, WHITE)


screen.blit(score_text, (20, 20))

pygame.display.update()

# Exit pygame
pygame.quit()
print(f"Game Over! Your Score: {score}")

callfun

def call(p=40,q=20):
p=p+q
q=p-q
print(p,'@',q)
return p
r=200
s=100
r=call(r,s)
print(r,'@',s)
s=call(s)
print(r,'@',s)

divisible by 7

def check():
n=a%7
return n
a=int(input("enter the number to check wether it is divisible by 7:"))
p=check()

if p==0:
print(a,"is divisible by 7")
else:
print(a,"is not divisible by 7")

reverse string

def reverse():
print(s[::-1])

s=input("Enter the string:")


reverse()

game

import turtle as t
import os

# Initialize Scores
playerAscore = 0
playerBscore = 0

# Create game window


window = t.Screen()
window.title("Pong Game")
window.bgcolor("green")
window.setup(width=800, height=600)
window.tracer(0)

# Left Paddle
leftpaddle = t.Turtle()
leftpaddle.speed(0)
leftpaddle.shape("square")
leftpaddle.color("white")
leftpaddle.shapesize(stretch_wid=5, stretch_len=1)
leftpaddle.penup()
leftpaddle.goto(-350, 0)

# Right Paddle (Fixed Position)


rightpaddle = t.Turtle()
rightpaddle.speed(0)
rightpaddle.shape("square")
rightpaddle.color("pink")
rightpaddle.shapesize(stretch_wid=5, stretch_len=1)
rightpaddle.penup()
rightpaddle.goto(350, 0) # Fixed position

# Ball
ball = t.Turtle()
ball.speed(40)
ball.shape("circle")
ball.color("red")
ball.penup()
ball.goto(0, 0)
ballxdirection = 0.2
ballydirection = 0.2

# Score Display
pen = t.Turtle()
pen.speed(0)
pen.color("blue")
pen.penup()
pen.hideturtle()
pen.goto(0, 260)
pen.write("Player A: 0 Player B: 0", align="center", font=('Arial', 24,
'normal'))

# Paddle Movement
def leftpaddleup():
y = leftpaddle.ycor()
if y < 250: # Prevent paddle from going off screen
leftpaddle.sety(y + 20)

def leftpaddledown():
y = leftpaddle.ycor()
if y > -240:
leftpaddle.sety(y - 20)

def rightpaddleup():
y = rightpaddle.ycor()
if y < 250:
rightpaddle.sety(y + 20)

def rightpaddledown():
y = rightpaddle.ycor()
if y > -240:
rightpaddle.sety(y - 20)

# Assign Keyboard Controls


window.listen()
window.onkeypress(leftpaddleup, 'w')
window.onkeypress(leftpaddledown, 's')
window.onkeypress(rightpaddleup, 'Up')
window.onkeypress(rightpaddledown, 'Down')

# Main Game Loop


while True:
window.update()

# Move Ball
ball.setx(ball.xcor() + ballxdirection)
ball.sety(ball.ycor() + ballydirection)

# Top and Bottom Collision


if ball.ycor() > 290:
ball.sety(290)
ballydirection *= -1

if ball.ycor() < -290:


ball.sety(-290)
ballydirection *= -1

# Left and Right Wall Collision (Score Update)


if ball.xcor() > 390:
ball.goto(0, 0)
ballxdirection *= -1
playerAscore += 1
pen.clear()
pen.write(f"Player A: {playerAscore} Player B: {playerBscore}",
align="center", font=('Arial', 24, 'normal'))
os.system("afplay wallhit.wav&") # Play sound

if ball.xcor() < -390:


ball.goto(0, 0)
ballxdirection *= -1
playerBscore += 1
pen.clear()
pen.write(f"Player A: {playerAscore} Player B: {playerBscore}",
align="center", font=('Arial', 24, 'normal'))
os.system("afplay wallhit.wav&") # Play sound

# Paddle Collision
if (340 < ball.xcor() < 350) and (rightpaddle.ycor() - 50 < ball.ycor() <
rightpaddle.ycor() + 50):
ball.setx(340)
ballxdirection *= -1
os.system("afplay paddle.wav&")

if (-350 < ball.xcor() < -340) and (leftpaddle.ycor() - 50 < ball.ycor() <
leftpaddle.ycor() + 50):
ball.setx(-340)
ballxdirection *= -1
os.system("afplay paddle.wav&")

fun2

import cv2
import matplotlib.pyplot as plt

loaded_img = cv2.imread(r"E:\IMG20250202115517.jpg")
loaded_img = cv2.cvtColor(loaded_img, cv2.COLOR_BGR2RGB)

plt.figure(figsize=(20,20))

plt.subplot(2,2,1)
plt.title("Original Image")
plt.imshow(loaded_img)
plt.axis("off")

gray_image = cv2.cvtColor(loaded_img, cv2.COLOR_RGB2GRAY)


plt.subplot(2,2,2)
plt.title("Grayscale Image")
plt.imshow(gray_image,cmap="gray")
plt.axis("off")

_, binary_img = cv2.threshold(gray_image, 225, 255, cv2.THRESH_BINARY_INV)


plt.subplot(2,2,3)
plt.title("Binary Image")
plt.imshow(binary_img,cmap="gray")
plt.axis("off")

contours, hierarchy = cv2.findContours(binary_img, cv2.RETR_TREE,


cv2.CHAIN_APPROX_SIMPLE)
final_image = cv2.drawContours(loaded_img, contours, -1, (0, 255, 0), 2)
plt.subplot(2,2,4)
plt.title("Contours detected Image")
plt.imshow(final_image,cmap="gray")
plt.axis("off")

plt.savefig('Contour_Detection_output_2.png', dpi = 1000,bbox_inches = 'tight')


plt.tight_layout()
plt.show()

snake gm
import pygame
import time
import random

# Initialize pygame
pygame.init()

# Set screen size


width, height = 600, 400
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Snake Game 🐍")

# Colors
white = (255, 255, 255)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)

# Snake settings
snake_block = 10
snake_speed = 15

# Fonts
font = pygame.font.SysFont("bahnschrift", 25)

# Function to draw the snake


def draw_snake(snake_block, snake_list):
for x in snake_list:
pygame.draw.rect(screen, green, [x[0], x[1], snake_block, snake_block])
# Function to display the score
def show_score(score):
value = font.render(f"Score: {score}", True, red)
screen.blit(value, [10, 10])

# Main function
def gameLoop():
game_over = False
game_close = False

# Snake starting position


x, y = width / 2, height / 2
dx, dy = 0, 0

# Snake body
snake_list = []
length_of_snake = 1

# Food position
food_x = random.randrange(0, width - snake_block, 10)
food_y = random.randrange(0, height - snake_block, 10)

clock = pygame.time.Clock()

while not game_over:


while game_close:
screen.fill(black)
message = font.render("Game Over! Press R to Restart or Q to Quit",
True, red)
screen.blit(message, [width / 6, height / 3])
show_score(length_of_snake - 1)
pygame.display.update()

for event in pygame.event.get():


if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_over = True
game_close = False
if event.key == pygame.K_r:
gameLoop()

for event in pygame.event.get():


if event.type == pygame.QUIT:
game_over = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
dx, dy = -snake_block, 0
elif event.key == pygame.K_RIGHT:
dx, dy = snake_block, 0
elif event.key == pygame.K_UP:
dx, dy = 0, -snake_block
elif event.key == pygame.K_DOWN:
dx, dy = 0, snake_block

# Update snake position


x += dx
y += dy
# Collision detection (Wall hit)
if x >= width or x < 0 or y >= height or y < 0:
game_close = True

screen.fill(black)
pygame.draw.rect(screen, blue, [food_x, food_y, snake_block, snake_block])

# Snake body growth


snake_head = [x, y]
snake_list.append(snake_head)
if len(snake_list) > length_of_snake:
del snake_list[0]

# Collision with itself


for segment in snake_list[:-1]:
if segment == snake_head:
game_close = True

draw_snake(snake_block, snake_list)
show_score(length_of_snake - 1)

pygame.display.update()

# Eating food
if x == food_x and y == food_y:
food_x = random.randrange(0, width - snake_block, 10)
food_y = random.randrange(0, height - snake_block, 10)
length_of_snake += 1

clock.tick(snake_speed)

pygame.quit()
quit()

gameLoop()

fun3
import numpy as np
import cv2
from matplotlib import pyplot as plt
img = cv2.imread(r"E:\IMG20250202093317.jpg")
img=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
plt.figure(figsize=(8,8))
plt.imshow(img,cmap="gray")
plt.axis('off')
plt.title("Original Image")
plt.show()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
plt.figure(figsize=(8,8))
plt.imshow(gray,cmap="gray")
plt.axis('off')
plt.title("GrayScale Image")
plt.show()
ret, thresh = cv2.threshold(gray, 0, 255,cv2.THRESH_BINARY_INV +cv2.THRESH_OTSU)
plt.figure(figsize=(8,8))
plt.imshow(thresh,cmap="gray")
plt.axis('off')
plt.title("Threshold Image")
plt.show()
kernel = np.ones((3, 3), np.uint8)
closing = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE,kernel, iterations = 15)
bg = cv2.dilate(closing, kernel, iterations = 1)
dist_transform = cv2.distanceTransform(closing, cv2.DIST_L2, 0)
ret, fg = cv2.threshold(dist_transform, 0.02*dist_transform.max(), 255, 0)
cv2.imshow('image', fg)
plt.figure(figsize=(8,8))
plt.imshow(fg,cmap="gray")
plt.axis('off')
plt.title("Segmented Image")
plt.show()

fun

import cv2
import numpy as np
import matplotlib.pyplot as plt

# Load the image


image_path = r"C:\Users\ADMIN\OneDrive\Pictures\Screenshots\Screenshot 2025-03-07
222830.png" # Ensure the correct image path
loaded_image = cv2.imread(image_path)

# Error handling if image is not found


if loaded_image is None:
raise FileNotFoundError(f"Error: Unable to load the image at '{image_path}'.
Check the file path.")

# Convert to RGB format (OpenCV loads images in BGR by default)


loaded_image = cv2.cvtColor(loaded_image, cv2.COLOR_BGR2RGB)

# Convert to grayscale
gray_image = cv2.cvtColor(loaded_image, cv2.COLOR_RGB2GRAY)

# Apply Gaussian Blur to reduce noise (optional but recommended)


blurred_image = cv2.GaussianBlur(gray_image, (5, 5), 0)

# Apply Canny edge detection


edged_image = cv2.Canny(blurred_image, threshold1=30, threshold2=100)

# Display the results


plt.figure(figsize=(20, 20))

plt.subplot(1, 3, 1)
plt.imshow(loaded_image)
plt.title("Original Image")
plt.axis("off")

plt.subplot(1, 3, 2)
plt.imshow(gray_image, cmap="gray")
plt.title("Grayscale Image")
plt.axis("off")

plt.subplot(1, 3, 3)
plt.imshow(edged_image, cmap="gray")
plt.title("Canny Edge Detected Image")
plt.axis("off") # Fixed missing subplot for edge-detected image

plt.show()
dataframe

import pandas as pd

data = {
'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eva'],
'Subject': ['Math', 'Science', 'English', 'History', 'Math'],
'Marks': [88, 76, 95, 67, 82],
'Grade': ['A', 'B', 'A+', 'C', 'B+']
}

df = pd.DataFrame(data)
print(df)

print("Basic Statistics for Marks:")


print(df['Marks'].describe())

sorted_df = df.sort_values(by='Marks', ascending=False)


print("\nDataFrame sorted by Marks (descending order):")
print(sorted_df)

filtered_df = df[df['Marks'] > 75]


print("\nRecords where Marks are above 75:")
print(filtered_df)

You might also like