0% found this document useful (0 votes)
37 views

Python Lab Manual Cse Format

Uploaded by

ovab4zkmvg
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)
37 views

Python Lab Manual Cse Format

Uploaded by

ovab4zkmvg
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/ 25

ST.

ANDREWS INSTITUTE
OF TECHNOLOGY & MANAGEMENT

Gurgaon Delhi (NCR)


Approved by AICTE, Govt. of India, New Delhi affiliated to
Maharshi Dayanand University
‘A’ Grade State University, accredited by NAAC

Session: 2024 – 2025

Bachelor of Technology

Computer Science & Technology

A Practical File

Python Programming Lab

Subject Code-LC-CSE-215G

Submitted To: Submitted


by: NAME:
(Assistant Professor) SEM:

ROLL

NO.:
St. Andrews Institute of Technology &
Management, Gurugram
Department of……………………………
Practical Lab Evaluation Sheet

Practical Viva- Remarks


Attendanc Practica Overal
S.No Program Date CO Performe Voce &
e (05) l File l (25)
d (10) (05) (05) Signatur
e
1 Compute the GCD of CO
two numbers. 1
2 Find the square root CO
of a number (Newton 1
‘s method)
3 Exponentiation CO
(power of a number) 4
4 Find the maximum of CO
a list of numbers 4
5 Linear search and CO
Binary search 2
6 Selection sort, CO
Insertion sort 2
7 Merge sort CO
2
8 First n prime CO
numbers 4
9 Multiply matrices CO
3
10 Programs that take CO
command line 4
arguments (word
count)
11 Find the most CO
frequent words in a 1
text read
from a file
12 Simulate elliptical CO
orbits in Pygame 3
13 Simulate bouncing CO
ball using Pygame 3

Average Marks

Approved & Verified by (Faculty Name) (Faculty Sign.)


⮚ Program 1: Compute the GCD of two numbers.

SOURCE CODE
import math
def compute_gcd(a, b):
gcd_value = math.gcd(a, b)
return gcd_value
# Example numbers
num1 = 60
num2 = 48
gcd_result = compute_gcd(num1, num2)
print(f"The GCD of {num1} and {num2} is: {gcd_result}")

OUTPUT
Program 2: Find the square root of a number Newton‘s method)

SOURCE CODE

def sqrt_newton(N, tolerance=1e-6, max_iterations=1000):

x = N / 2 if N > 1 else N

for _ in range(max_iterations):

x_next = (x + N / x) / 2

if abs(x_next - x) < tolerance:

return x_next

x = x_next

return x

N = 25

result = sqrt_newton(N)

print(f"The square root of {N} is approximately: {result}")

OUTPUT
⮚ Program 3: Exponentiation (power of a number)

SOURCE CODE

base = 8

exponent = 3

result = pow(base, exponent)

print(result) # Output: 512

OUTPUT
⮚ Program 4: Find the maximum of a list of numbers

SOURCE CODE

numbers = [15,78,89,58,45]

numbers.sort()

max_value = numbers[-1]

print("The maximum value is:", max_value)

OUTPUT
⮚ Program 5: Linear search and Binary search

LINEAR SEARCH
SOURCE CODE

def linear_search(arr, target):

for i in range(len(arr)):

if arr[i] == target:

return i

return -1

arr = [37, 89, 45, 78, 25, 14]

target = 78

result = linear_search(arr, target)

if result != -1:

print(f"Element is present at index {result}")

else:

print("Target not found")

OUTPUT
BINARY SEARCH
SOURCE CODE
def binary_search(arr, target):

left, right = 0, len(arr) - 1

while left <= right:


mid = left + (right - left) // 2

if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1

return -1

arr = [14,69,56,15,69,69]
target = 69

result = binary_search(arr, target)


if result != -1:
print(f"Target found at index: {result}")
else:
print("Target not found")

OUTPUT
⮚ Program 6: Selection sort, Insertion sort

SELECTION SORT
SOURCE CODE

def selection_sort(arr):
for i in range(len(arr)):
min_index = i
for j in range(i + 1, len(arr)):
if arr[j] < arr[min_index]:
min_index = j

arr[i], arr[min_index] = arr[min_index], arr[i]

arr = [64, 15, 5, 89, 8]


selection_sort(arr)
print("Sorted array:", arr)

OUTPUT
INSERTION SORT
SOURCE CODE
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j=i-1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1

arr[j + 1] = key

arr = [65,78,98,91,12,8]
insertion_sort(arr)
print("Sorted array:", arr)

OUTPUT
⮚ Program 7: Merge sort
SOURCE CODE
def merge_sort(arr):
if len(arr) <= 1:
return arr

mid = len(arr) // 2

left_half = merge_sort(arr[:mid])
right_half = merge_sort(arr[mid:])

return merge(left_half, right_half)

def merge(left, right):


result = []
i=j=0

while i < len(left) and j < len(right):


if left[i] < right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1

result.extend(left[i:])
result.extend(right[j:])

return result

# Example usage:
arr = [38, 27, 43, 3, 9, 82, 10]
sorted_arr = merge_sort(arr)
print("Sorted array:", sorted_arr)

OUTPUT
⮚ Program 8: First n prime numbers

SOURCE CODE

def is_prime(num):

if num <= 1:

return False

for i in range(2, int(num**0.5) + 1):

if num % i == 0:

return False

return True

def first_n_primes(n):

primes = []

num = 2

while len(primes) < n:

if is_prime(num):

primes.append(num)

num += 1

return primes

n = 10

print(first_n_primes(n))

OUTPUT
⮚ Program 9: Multiply matrices

SOURCE CODE

def multiply_matrices(A, B):

m = len(A)

n = len(A[0])

p = len(B[0])

C = [[0] * p for _ in range(m)]

for i in range(m):

for j in range(p):

for k in range(n):

C[i][j] += A[i][k] * B[k][j]

return C

A = [[1, 2, 3],

[4, 5, 6]]

B = [[7, 8],

[9, 10],

[11, 12]]

C = multiply_matrices(A, B)

for row in C:

print(row)

OUTPUT
⮚ Program 10: Programs that take command line arguments (word
count)
SOURCE CODE

import sys

from collections import Counter

import string

# Function to count the frequency of words in command line arguments

def word_count_from_args():

# Check if we have at least one argument (besides the script name)

if len(sys.argv) < 2:

print("Please provide some text as command line arguments.")

return

# Combine all the command line arguments into a single string (excluding the script
name)

input_text = " ".join(sys.argv[1:]).lower() # Join all arguments and convert to


lowercase

# Remove punctuation from the text

translator = str.maketrans('', '', string.punctuation)

cleaned_text = input_text.translate(translator)

# Split the cleaned text into words

words = cleaned_text.split()

# Count the frequency of each word using Counter

word_counts = Counter(words)

# Display the word counts

print("Word counts:")
for word, count in word_counts.items():

print(f"{word}: {count}")

# Run the program

if __name__ == "__main__":

word_count_from_args()

AND Save the Python code in this file word_count.py.

OUTPUT
⮚ Program 11: Find the most frequent words in a text read from a
file
SOURCE CODE

import string

from collections import Counter

# Function to read the text from the file and find the most frequent words

def find_most_frequent_words(filename, top_n=10):

try:

# Step 1: Read the file

with open(filename, 'r') as file:

text = file.read().lower() # Read and convert the text to lowercase

except FileNotFoundError:

print(f"The file {filename} was not found.")

return

# Step 2: Remove punctuation using translate

translator = str.maketrans('', '', string.punctuation)

text_cleaned = text.translate(translator)

# Step 3: Split the cleaned text into words

words = text_cleaned.split()

# Step 4: Count the frequency of each word using Counter

word_counts = Counter(words)

# Step 5: Get the most common words

most_common = word_counts.most_common(top_n)

# Step 6: Display the results


print(f"The {top_n} most frequent words in the text are:")

for word, count in most_common:

print(f"{word}: {count}")

# Example usage

filename = 'sample_text.txt' # Change this to your text file path

find_most_frequent_words(filename, top_n=10)

AND text file (sample_text.txt)

Python is a great programming language. Python is easy to learn, and Python has a
rich ecosystem.

Python is used for web development, data analysis, artificial intelligence, and more.

OUTPUT
⮚ Program 12: Simulate elliptical orbits in Pygame

SOURCE CODE

import pygame

import math

import sys

# Initialize Pygame

pygame.init()

# Constants

WIDTH, HEIGHT = 800, 600 # Screen dimensions

FPS = 60 # Frames per second

WHITE = (255, 255, 255)

SUN_COLOR = (255, 255, 0)

PLANET_COLOR = (0, 0, 255)

ORBIT_COLOR = (200, 200, 200)

# Ellipse parameters

a = 300 # Semi-major axis (horizontal)

b = 200 # Semi-minor axis (vertical)

# Sun parameters (focus)

sun_pos = (WIDTH // 2, HEIGHT // 2) # Sun at the center

# Planet parameters

planet_radius = 10 # Radius of the planet

planet_angle = 0 # Starting angle


# Create the Pygame window

screen = pygame.display.set_mode((WIDTH, HEIGHT))

pygame.display.set_caption("Elliptical Orbit Simulation")

# Simulation loop

clock = pygame.time.Clock()

while True:

for event in pygame.event.get():

if event.type == pygame.QUIT:

pygame.quit()

sys.exit()

# Calculate the position of the planet

planet_x = sun_pos[0] + a * math.cos(planet_angle) # Elliptical X position

planet_y = sun_pos[1] + b * math.sin(planet_angle) # Elliptical Y position

# Update the angle for the next frame (simulate constant angular velocity)

planet_angle += 0.01 # This value controls the speed of the orbit

# Clear the screen

screen.fill(WHITE)

# Draw the orbit (ellipse)

pygame.draw.ellipse(screen, ORBIT_COLOR, (sun_pos[0] - a, sun_pos[1] - b,


2 * a, 2 * b), 1)
# Draw the sun (focus of the ellipse)

pygame.draw.circle(screen, SUN_COLOR, sun_pos, 20)

# Draw the planet

pygame.draw.circle(screen, PLANET_COLOR, (int(planet_x), int(planet_y)),


planet_radius)

# Update the display

pygame.display.flip()

# Maintain the framerate

clock.tick(FPS)

OUTPUT
⮚ Program 13: Simulate bouncing ball using Pygame

SOURCE CODE

import pygame

import sys

# Initialize Pygame

pygame.init()

# Constants

WIDTH, HEIGHT = 800, 600 # Screen dimensions

BALL_RADIUS = 20 # Radius of the ball

BALL_COLOR = (255, 0, 0) # Color of the ball (Red)

BACKGROUND_COLOR = (255, 255, 255) # Background color (White)

FPS = 60 # Frames per second

# Gravity constant

GRAVITY = 0.5 # Affects the ball's downward acceleration

# Create the Pygame window

screen = pygame.display.set_mode((WIDTH, HEIGHT))

pygame.display.set_caption("Bouncing Ball Simulation")

# Ball initial parameters

ball_x = WIDTH // 2 # Start at the center of the screen

ball_y = HEIGHT // 2

ball_velocity_x = 4 # Horizontal velocity (px per frame)


ball_velocity_y = 0 # Initial vertical velocity (starts at 0)

bounce_damping = 0.8 # Reduces velocity when bouncing to simulate


energy loss

# Simulation loop

clock = pygame.time.Clock()

while True:

for event in pygame.event.get():

if event.type == pygame.QUIT:

pygame.quit()

sys.exit()

# Update ball's vertical velocity with gravity

ball_velocity_y += GRAVITY

# Update the ball's position based on its velocity

ball_x += ball_velocity_x

ball_y += ball_velocity_y

# Ball collision with the left and right walls (horizontal boundaries)

if ball_x - BALL_RADIUS < 0 or ball_x + BALL_RADIUS > WIDTH:

ball_velocity_x = -ball_velocity_x # Reverse the horizontal velocity

# Ball collision with the top wall

if ball_y - BALL_RADIUS < 0:

ball_velocity_y = -ball_velocity_y # Reverse the vertical velocity


# Ball collision with the floor (bottom of the screen)

if ball_y + BALL_RADIUS > HEIGHT:

ball_y = HEIGHT - BALL_RADIUS # Keep the ball on the floor

ball_velocity_y = -ball_velocity_y * bounce_damping # Reverse the


velocity and apply damping

# Fill the screen with the background color

screen.fill(BACKGROUND_COLOR)

# Draw the ball (circle)

pygame.draw.circle(screen, BALL_COLOR, (ball_x, ball_y),


BALL_RADIUS)

# Update the display

pygame.display.flip()

# Maintain the framerate

clock.tick(FPS)

OUTPUT

You might also like