Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
26 views

Sample Copy Python CS506

hello sir ji

Uploaded by

dhruvsharmadrsh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Sample Copy Python CS506

hello sir ji

Uploaded by

dhruvsharmadrsh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

RUSTAMJI INSTITUTE OF TECHNOLOGY

BSF ACADEMY, TEKANPUR


TABLE OF CONTENTS
S. No. Practical Description Page Nos.

1 To write a Python program to find GCD of two numbers. 1

2 To write a Python Program to find the square root of a 2


number by Newton’s Method.

3 To write a Python program to find the exponentiation of a 3


number.

4 To write a Python Program to find the maximum from a list 4


of numbers.

5 To write a Python Program to perform Linear Search 5

6 To write a Python Program to perform binary search. 6

7 To write a Python Program to perform selection sort. 8

8 To write a Python Program to perform insertion sort. 9

9 To write a Python Program to perform Merge sort. 10

10 To write a Python program to find first n prime numbers. 13

11 To write a Python program to multiply matrices. 14

12 To write a Python program for command line arguments. 15

13 To write a Python program to find the most frequent words 16


in a text read from a file.

14 To write a Python program to simulate elliptical orbits in 17


Pygame.

15 To write a Python program to bounce balls in Pygame. 19


EXPRERIMENT-01
Q1. Write a Python program to find GCD of two numbers.
ANS :

def gcd(a, b):


while b:
a, b = b, a % b
return a
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
result = gcd(num1, num2)
print(f"The GCD of {num1} and {num2} is {result}")

Output:-
Enter the first number: 23
Enter the second number: 22
The GCD of 23 and 22 is 1

[Type here]
EXPERIMENT- 02
Q2. To write a Python Program to find the square root of a number by Newton’s
Method.
ANS:
def newton_sqrt(n, tolerance=1e-10):
x=n
while True:
root = 0.5 * (x + n / x)
if abs(root - x) < tolerance:
return root
x = root
number = float(input("Enter a number to find the square root: "))
sqrt_value = newton_sqrt(number)
print(f"The square root of {number} is approximately {sqrt_value}")

output:-
Enter a number to find the square root: 144

The square root of 144.0 is approximately 12.0

[Type here]
EXPERIMENT-03
Description: To write a Python program to find the exponentiation of a number.
ANS:

def exponentiate(base, exponent):

result = 1

for _ in range(exponent):

result *= base

return result

base = float(input("Enter the base number: "))

exponent = int(input("Enter the exponent: "))

exp_value = exponentiate(base, exponent)

print(f"{base} raised to the power of {exponent} is {exp_value}")

Output:-

Enter the base number: 4


Enter the exponent: 3
4.0 raised to the power of 3 is 64.0

[Type here]
EXPERIMENT-04
Description: To write a Python Program to find the maximum from a list of numbers.

ANS:

def find_max(numbers):
max_num = numbers[0]
for num in numbers:
if num > max_num:
max_num = num
return max_num
numbers = list(map(int, input("Enter a list of numbers separated by spaces: ").split()))
max_value = find_max(numbers)
print(f"The maximum number in the list is: {max_value}")

Output-
Enter a list of numbers separated by spaces: 12 13 11 2 3 4 5 6 7 8 9
The maximum number in the list is: 13

[Type here]
EXPERIMENT-05
Description: write a program to implement linear search on list .

ANS:

def linear_search(numbers, target):

# Iterate through the list and check each element

for index, num in enumerate(numbers):

# If the target is found, return the index

if num == target:

return index

# If the target is not found, return -1

return -1

# Example usage

numbers = list(map(int, input("Enter a list of numbers separated by spaces: ").split()))

target = int(input("Enter the number to search for: "))

result = linear_search(numbers, target)

if result != -1:

print(f"Number found at index {result}")

else:

print("Number not found in the list")

Output:-
Enter a list of numbers separated by spaces: 12 33 4 5 74 324 242 4245
Enter the number to search for: 5
Number found at index 3

[Type here]
EXPERIMENT-06
Description: Write a program to perform binary search
Solution:-

def binary_search(numbers, target):


left, right = 0, len(numbers) - 1
while left <= right:
mid = (left + right) // 2
if numbers[mid] == target:
return mid
elif numbers[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1

numbers = sorted(list(map(int, input("Enter a sorted list of numbers separated by spaces: ").split())))


target = int(input("Enter the number to search for: "))
result = binary_search(numbers, target)

if result != -1:
print(f"Number found at index {result}")
else:
print("Number not found in the list")

Output:-

Enter a sorted list of numbers separated by spaces: 12 14 22 26 77 83

Enter the number to search for: 77

Number found at index 4

[Type here]
EXPERIMENT - 07
Description: Write a program to implement selection sort
Solution:-

def selection_sort(numbers):

for i in range(len(numbers)):

min_index = i

for j in range(i + 1, len(numbers)):

if numbers[j] < numbers[min_index]:

min_index = j

numbers[i], numbers[min_index] = numbers[min_index], numbers[i]

numbers = list(map(int, input("Enter a list of numbers separated by spaces: ").split()))

selection_sort(numbers)

print("Sorted list:", numbers)

Output:-
Enter a list of numbers separated by spaces: 1 22 13 1 24 22 2 34

Sorted list: [1, 1, 2, 13, 22, 22, 24, 34]

[Type here]
EXPERIMENT - 08
Description: To write a Python Program to perform insertion sort.
ANS:
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j=i-1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
arr = list(map(int, input("Enter numbers separated by spaces: ").split()))
sorted_arr = insertion_sort(arr)
print("Sorted array:", sorted_arr)

Output:-
Enter numbers separated by spaces: 12 11 13 5 6
Sorted array: [5, 6, 11, 12, 13]

[Type here]
EXPERIMENT - 09
Description :To write a Python Program to perform Merge sort.

ANS:
def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]

merge_sort(left_half)
merge_sort(right_half)

i=j=k=0

while i < len(left_half) and j < len(right_half):


if left_half[i] < right_half[j]:
arr[k] = left_half[i]
i += 1
else:
arr[k] = right_half[j]
j += 1
k += 1

while i < len(left_half):


arr[k] = left_half[i]
i += 1
k += 1

while j < len(right_half):


arr[k] = right_half[j]

[Type here]
j += 1
k += 1

return arr

# Taking input from user


arr = list(map(int, input("Enter numbers separated by spaces: ").split()))
sorted_arr = merge_sort(arr)
print("Sorted array:", sorted_arr)

Output:-
Enter numbers separated by spaces: 38 27 43 3 9 82 10

Sorted array: [3, 9, 10, 27, 38, 43, 82]

[Type here]
EXPERIMENT - 10
Description: Write a program to find first n prime numbers.
ANS:
def is_prime(num):
if num < 2:
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 = int(input("Enter the value of n: "))
prime_numbers = first_n_primes(n)
print("First", n, "prime numbers:", prime_numbers)

Output:-
Enter the value of n: 10
First 10 prime numbers: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

[Type here]
EXPERIMENT - 11
Description: Write a program to multiply two matrices.
ANS:
def take_input(rows, cols, matrix_name):
matrix = []
print(f"Enter {matrix_name} elements in a single line, space-separated:")
elements = list(map(int, input().split()))

for i in range(rows):
row = elements[i * cols:(i + 1) * cols]
matrix.append(row)

return matrix

def matrix_multiply(A, B):


result = [[0 for _ in range(len(B[0]))] for _ in range(len(A))]
for i in range(len(A)):
for j in range(len(B[0])):
for k in range(len(B)):
result[i][j] += A[i][k] * B[k][j]
return result

A = take_input(2, 3, "Matrix A")


B = take_input(3, 2, "Matrix B")
result = matrix_multiply(A, B)
flattened_result = [item for sublist in result for item in sublist]
print("Resultant Matrix after multiplication in a single array:")
print(flattened_result)

[Type here]
Output:-
Enter Matrix A elements in a single line, space-separated:
123456
Enter Matrix B elements in a single line, space-separated:
7 8 9 10 11 12
Resultant Matrix after multiplication in a single array:
[58, 64, 139, 154]

[Type here]
EXPERIMENT - 12
Description: write a program for command line arguments.
ANS:
import sys

n = len(sys.argv)

print("Total arguments passed:", n)

print("\nName of Python script:", sys.argv[0])

print("\nArguments passed:", end = " ")

for i in range(1, n):

print(sys.argv[i], end = " ")

Sum = 0

# Using argparse module

for i in range(1, n):

Sum += int(sys.argv[i])

print("\n\nResult:", Sum)

Output:-

[Type here]
EXPERIMENT - 13
Practical Description: write a program to count the most frequent word in a text file

Solution:-

count = 0;

word = "";

maxCount = 0;

words = [];

#Opens a file in read mode

file = open("data.txt", "r")

for line in file:

string = line.lower().replace(',','').replace('.','').split(" ");

for s in string:

words.append(s);

for i in range(0, len(words)):

count = 1;

for j in range(i+1, len(words)):

if(words[i] == words[j]):

count = count + 1;

if(count > maxCount):

maxCount = count;

word = words[i];

print("Most repeated word: " + word);

file.close();

output:-

[Type here]
EXPERIMENT - 14
Practical Description: write a program to simulate elliptical orbit in pygame

Solution:-

import pygame

import math

import sys

pygame.init()

screen = pygame.display.set_mode((600, 300))

pygame.display.set_caption("Elliptical orbit")

#creating clock variable

clock=pygame.time.Clock()

while(True):

for event in pygame.event.get():

if event.type == pygame.QUIT:

sys.exit()

xRadius = 250

yRadius = 100

for degree in range(0,360,10):

x1 = int(math.cos(degree * 2 * math.pi/360) * xRadius)+300

y1 = int(math.sin(degree * 2 * math.pi/360) * yRadius)+150

screen.fill((0, 0, 0))

pygame.draw.circle(screen, (255, 69, 0), [300, 150], 40)

pygame.draw.ellipse(screen,(255,255,255),[50,50,500,200],1)

pygame.draw.circle(screen, (0, 255, 0), [x1, y1], 20)

pygame.display.flip()

clock.tick(5)# screen refresh rate

[Type here]
Output:-

[Type here]
EXPERIMENT - 15
Practical Description: write a program for bouncing ball in pygame

Solution:-

import sys, pygame

pygame.init()

size = width, height = 800,400

speed = [1, 1]

background = 255, 255, 255

screen = pygame.display.set_mode(size)

pygame.display.set_caption("Bouncing ball")

ball = pygame.image.load("ball.png")

ballrect = ball.get_rect()

while 1:

for event in pygame.event.get():

if event.type == pygame.QUIT:

sys.exit()

ballrect = ballrect.move(speed)

[Type here]
if ballrect.left < 0 or ballrect.right > width:

speed[0] = -speed[0]

if ballrect.top < 0 or ballrect.bottom > height:

speed[1] = -speed[1]

screen.fill(background)

screen.blit(ball, ballrect)

pygame.display.flip()

Output:-

For check the demo of bouncing ball program click the ball image above

[Type here]

You might also like