0% found this document useful (0 votes)
4 views41 pages

Python Record With Front Page and Result

The document outlines a series of programming experiments conducted at the Nehru Institute of Technology, focusing on problem-solving and Python programming. Each experiment includes an aim, algorithm, program code, output, and result, covering topics such as finding minimum values in lists, inserting cards in sorted lists, and implementing binary search. The document serves as a practical record of the work done by students in the laboratory during their academic year.

Uploaded by

jersonm06xx
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)
4 views41 pages

Python Record With Front Page and Result

The document outlines a series of programming experiments conducted at the Nehru Institute of Technology, focusing on problem-solving and Python programming. Each experiment includes an aim, algorithm, program code, output, and result, covering topics such as finding minimum values in lists, inserting cards in sorted lists, and implementing binary search. The document serves as a practical record of the work done by students in the laboratory during their academic year.

Uploaded by

jersonm06xx
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/ 41

Nehru Institute of Technology

(Autonomous)
Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai
Recognized by UGC with Section 2(f), Accredited by NAAC with A+, NBA Accredited

U23GE201- PROBLEM SOLVING AND PYTHON


PROGRAMMING

Certified that this is the bonafide record of work done by …..…………..……………………..

in the………………………………………………………………………………laboratory of

this institution, as prescribed by the Autonomous Regulation …………………..for

the………………… Semester B.E/B.Tech., during the academic year …………………..

Faculty in-charge: HOD:

Date: Date:

Register No :

Submitted for the (……………………………………………………..) B.E/B.Tech.,

Examination Practical conducted on………………………………………………..

Internal Examiner External Examiner


Nehru Institute of Technology
(Autonomous)
Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai
Recognized by UGC with Section 2(f), Accredited by NAAC with A+, NBA Accredited

INDEX
Pg
Exp.No. DATE EXPERIMENT NAME MARK SIGN
No.
Nehru Institute of Technology
(Autonomous)
Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai
Recognized by UGC with Section 2(f), Accredited by NAAC with A+, NBA Accredited

Average
Exp No: 1
Find Minimum in a List
Date :

AIM:
To find the minimum value in a list of numbers.

ALGORITHM:
Step-1. Initialize a variable min_value with the first element of the list.
Step-2. Iterate through the remaining elements of the list.
Step-3. For each element, if it's smaller than min_value, update min_value to
that element.
Step-4. After iterating through all elements, min_value will hold the
minimum value in the list.
PROGRAM:

01 # A Python Program to Find Minimum in a List


02 def find_minimum(lst):
03 # Initialize min_value with the first element of the list
04 min_value = lst[0]
05
06 # Iterate through the list starting from the second element
07 for num in lst[1:]:
08 # If the current number is smaller than min_value, update min_value
09 if num < min_value:
10 min_value = num
11
12 return min_value
13
14 # Example usage:
15 numbers = [5, 3, 9, 2, 7, 1]
16 min_number = find_minimum(numbers)
17 print("The minimum value in the list is:", min_number)

1
OUTPUT:

RESULT:

Thus, The mini minimum value in list of numbers in found successfully

2
Exp No: 2
Insert a Card in a List of Sorted Cards
Date :

AIM:
To insert a card into a list of sorted cards while keeping the list sorted.

ALGORITHM:

Step-1. Start by identifying the correct position where the new card should be
inserted to maintain the sorted order.
Step-2. Iterate through the sorted list.
Step-3. Compare the value of the new card with each card in the sorted list
until you find a card with a greater value or reach the end of the list.
Step-4. Once you find the correct position, insert the new card at that index
in the list.
Step-5. The list remains sorted with the new card inserted.

PROGRAM:

01 # A Python Program to Insert a Card in a List of Sorted Cards


02
03 def insert_card(sorted_cards, new_card):
04 # Initialize index to insert the new card
05 insert_index = 0
06
07 # Find the correct position to insert the new card
08 while insert_index < len(sorted_cards) and sorted_cards[insert_index]
< new_card:
09 insert_index += 1
10
11 # Insert the new card at the identified position
12 sorted_cards.insert(insert_index, new_card)
13
14 # Example usage:

3
15 sorted_cards = [2, 4, 6, 8, 10]
16 new_card = 5
17 insert_card(sorted_cards, new_card)
18
19 print("Sorted cards after inserting", new_card, ":", sorted_cards)

OUTPUT:

RESULT:

Thus, the operation is completed successfully

4
Exp No: 3
Guess an Integer Number in a Range
Date :

AIM:
To create a program that guesses an integer number within a specified range.

ALGORITHM:

Step-1. Define the range within which the number should be guessed.
Step-2. Initialize a variable to store the guessed number.
Step-3. Use a guessing strategy to narrow down the range of possible
numbers until the correct number is guessed.
Step-4. Output the guessed number.

PROGRAM:

01 # A Python Program to Guess an Integer Number in a Range


02
03 import random
04
05 def guess_number(lower_bound, upper_bound):
06 # Generate a random number within the specified range
07 guessed_number = random.randint(lower_bound, upper_bound)
08 return guessed_number
09
10 # Example usage:
11 lower_bound = 1
12 upper_bound = 100
13 guessed_number = guess_number(lower_bound, upper_bound)
14 print("Guessed number:", guessed_number)

5
OUTPUT:

RESULT:

Thus, the program that guesses an integer number within a specified range has been
successfully created

6
Exp No: 4
Towers of Hanoi
Date :

AIM:
To solve the Towers of Hanoi problem for a given number of disks, moving
them from one peg to another, obeying the rules of the game.

ALGORITHM:

Step-1. Define three pegs: source (where the disks start), auxiliary (a spare
peg), and destination (where the disks should end up).
Step-2. Recursively move the top n-1 disks from the source peg to the
auxiliary peg, using the destination peg as a temporary location.
Step-3. Move the largest disk from the source peg to the destination peg.
Step-4. Recursively move the n-1 disks from the auxiliary peg to the
destination peg, using the source peg as a temporary location.

PROGRAM:

01 # A Python Program for Towers of Hanoi


02 def towers_of_hanoi(n, source, auxiliary, destination):
03 if n == 1:
04 print("Move disk 1 from", source, "to", destination)
05 return
06 towers_of_hanoi(n-1, source, destination, auxiliary)
07 print("Move disk", n, "from", source, "to", destination)
08 towers_of_hanoi(n-1, auxiliary, source, destination)
09
10 # Example usage:
11 n = 3 # Number of disks
12 source_peg = "A"
13 auxiliary_peg = "B"

7
14 destination_peg = "C"
15 print("Steps to solve the Towers of Hanoi with", n, "disks:")
16 towers_of_hanoi(n, source_peg, auxiliary_peg, destination_peg)

OUTPUT:

RESULT:

Tower of Hanoi problem has been solved successfully

8
Exp No: 5
Exchange the Values of Two Variables
Date :

AIM:
The aim of this program is to exchange the values of two variables.

ALGORITHM:

Step-1. Start
Step-2. Initialize two variables, a and b, with some values.
Step-3. Print the values of a and b before swapping.
Step-4. Exchange the values of a and b using a temporary variable.
Step-5. Print the values of a and b after swapping.
Step-6. Stop

PROGRAM:

01 # A Python Program to Exchange the Values of Two Variables


02
03 a = int(input("Enter the value of a: "))
04 b = int(input("Enter the value of b: "))
05
06 print("Before swapping:")
07 print("a = ", a)
08 print("b = ", b)
09
10 # Using a temporary variable
11 temp = a
12 a=b
13 b = temp
14
15 print("\nAfter swapping:")

9
16 print("a = ", a)
17 print("b = ", b)

OUTPUT:

RESULT:

Thus, values of two variables were exchanged successfully

10
Exp No: 6
Circulate the Values of n Variables
Date :

AIM:
The aim of this program is to circulate the values of n variables.

ALGORITHM:

Step-1. Start
Step-2. Initialize n variables with some values.
Step-3. Print the values of all variables before circulating.
Step-4. Circulate the values of the variables.
Step-5. Print the values of all variables after circulating.
Step-6. Stop

PROGRAM:

01 # A Python Program to Circulate the values of n variables


02 a = int(input("Enter the value of a: "))
03 b = int(input("Enter the value of b: "))
04 c = int(input("Enter the value of c: "))
05 d = int(input("Enter the value of d: "))
06
07 print("Before circulating:", a, b, c, d)
08
09 # Circulating values
10 temp = a
11 a=b
12 b =c
13 c=d
14 d = temp
16 print("\nAfter circulating:", a, b, c, d)

11
OUTPUT:

RESULT:

Thus, program is to circulate the values of n variables is created successfully

12
Exp No: 7
Distance between Two points
Date :

AIM:
To calculate the distance between two points in a two-dimensional space.

ALGORITHM:

Step-1. Given two points with coordinates (x1, y1) and (x2, y2),
Step-2. where (x1, y1) represents the coordinates of the first point and (x2,
y2) represents the coordinates of the second point.
Step-3. Use the Euclidean distance formula to calculate the distance between
the two points
Step-4. Distance = ?((x2 - x1)^2 + (y2 - y1)^2)

PROGRAM:

01 # A Python Program to Find Distance between Two points


02 import math
03
04 def calculate_distance(x1, y1, x2, y2):
05 distance = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
06 return distance
07
08 # Example usage:
09 x1, y1 = 1, 2 # Coordinates of the first point
10 x2, y2 = 4, 6 # Coordinates of the second point
11 distance = calculate_distance(x1, y1, x2, y2)
12 print("Distance between the two points:", distance)
13

13
OUTPUT:

RESULT:

Thus, the distance between two points in a two-dimensional space is found


successfully

14
Exp No: 8
Simple Square root, Exponentiation
Date :

AIM:
To calculate the square root and exponentiation of a number using Python.

ALGORITHM:
Step-1. Square Root: Use the math.sqrt() function from the math module
Step-2. to calculate the square root of a number.
Step-3. Exponentiation: Use the ** operator to perform exponentiation in
Python.
Step-4. For example, a ** b calculates a^b.

PROGRAM:

01 # A Python Program to Find Simple Square root, Exponentiation


02 import math
03
04 # Function to calculate square root
05 def calculate_square_root(number):
06 square_root = math.sqrt(number)
07 return square_root
08
09 # Function to perform exponentiation
10 def calculate_exponentiation(base, exponent):
11 result = base ** exponent
12 return result
13
14 # Example usage for square root
15 number = 16
16 square_root = calculate_square_root(number)
17 print("Square root of", number, ":", square_root)
18
19 # Example usage for exponentiation
20 base = 2
21 exponent = 3
22 result = calculate_exponentiation(base, exponent)
23 print(base, "raised to the power of", exponent, ":", result)

15
OUTPUT:

RESULT:

Thus, The square root and exponentiation of a number using Python is


successfully completed.

16
Exp No: 9
Voter’s Age Validation
Date :

AIM:
To validate whether a person's age qualifies them to vote.

ALGORITHM:
Step-1. Prompt the user to input their age.
Step-2. Check if the age is greater than or equal to the minimum voting age
(usually 18 years old).
Step-3. If the age meets the criteria, display a message indicating that the
person is eligible to vote.
Step-4. If the age does not meet the criteria, display a message indicating that
the person is not eligible to vote.

PROGRAM:

01 # A Python Program for Voter’s Age Validation


02 def validate_voter_age(age):
03 minimum_voting_age = 18
04 if age >= minimum_voting_age:
05 print("You are eligible to vote!")
06 else:
07 print("You are not eligible to vote yet.")
08
09 # Example usage:
10 age = int(input("Enter your age: "))
11 validate_voter_age(age)

17
OUTPUT:

RESULT:

Thus, the voter validation program is completed successfully

18
Exp No: 10
Pyramid Pattern
Date :

AIM:
The aim of this program is to print a pyramid pattern using iterative loops and
conditionals.

ALGORITHM:
Step-1. Start
Step-2. Prompt the user to input the number of rows for the pyramid pattern.
Step-3. Generate and print the pyramid pattern using iterative loops and
conditionals.
Step-4. Stop

PROGRAM:
1 # A Python Program for Pyramid Pattern
2 # Print a pyramid pattern of asterisks
3 rows = int(input("Enter the number of rows for the pyramid pattern: "))
4
5 for i in range(1, rows + 1):
6 print(" " * (rows - i) + "* " * i)

19
OUTPUT:

RESULT:

Thus, pyramid pattern using iterative loops and conditionals is performed


successfully

20
Exp No: 11
Binary Search
Date :

AIM:
The aim of this program is to do binary search in a list of numbres.

ALGORITHM:
Step-1. Given a sorted array and a target value to search.
Step-2. Set two pointers, low and high, initially pointing to the first and last
elements of the array, respectively.
Step-3. While low is less than or equal to high, do:
Step-4. Calculate the middle index as (low + high) // 2.
Step-5. If the middle element is equal to the target, return its index.
Step-6. If the middle element is greater than the target, update high to mid -
1.
Step-7. If the middle element is less than the target, update low to mid + 1.
Step-8. If the target is not found in the array, return -1.

21
PROGRAM:
01 # A Python Program for Binary Search
02
03 def binary_search(arr, target):
04 low = 0
05 high = len(arr) - 1
06
07 while low <= high:
08 mid = (low + high) // 2
09 if arr[mid] == target:
10 return mid
11 elif arr[mid] < target:
12 low = mid + 1
13 else:
14 high = mid - 1
15
16 return -1
17
18 # Example usage:
19 arr = [2, 3, 5, 7, 9, 11, 13]
20 print (arr)
21 target = int(input("Enter the target element: "))
22 result = binary_search(arr, target)
23
24 if result != -1:
25 print("Element ", target, " is present at index ", result)
26 else:
27 print("Element ", target, " is not present in the array.")
28

22
OUTPUT:

RESULT:

Thus, Binary search to find list of numbers is completed successfully

23
Exp No: 12
Linear Search
Date :

AIM:
The aim of this program is to search for a target value in a list using the linear
search algorithm.

ALGORITHM:
Step-1. Given a list and a target value to search.
Step-2. Iterate through each element in the list:
Step-3. If the current element is equal to the target, return its index.
Step-4. If the target is not found in the list, return -1.

PROGRAM:
01 # A Python Program for Linear Search
02 def linear_search(arr, target):
03 for index in range(len(arr)):
04 if arr[index] == target:
05 return index
06 return -1
07
08 # Example usage:
09 arr = [10, 20, 30, 40, 50]
10 print(arr)
11 target = int(input("Enter Target Element: "))
12 result = linear_search(arr, target)
13
14 if result != -1:
15 print("Element ", target, " is present at index ", result)
16 else:
17 print("Element ", target, " is not present in the list.")
18

24
OUTPUT:

RESULT:

Thus, search for a target value in a list using the linear search algorithm is
completed successfully

25
Exp No: 13
Simple Sorting
Date :

AIM:
The aim of this program is to sort a list of numbers using the bubble sort
algorithm.

ALGORITHM:
Step-1. Given a list of numbers.
Step-2. Repeat the following steps for each element in the list:
Step-3. Iterate through the list from the beginning to the end.
Step-4. Compare each pair of adjacent elements.
Step-5. If the current element is greater than the next element, swap them.
Step-6. Repeat step 2 until no swaps are needed (the list is sorted).

PROGRAM:
01 # A Python Program for Bubble Sort
02 def bubble_sort(arr):
03 n = len(arr)
04 for i in range(n):
05 for j in range(0, n - i - 1):
06 if arr[j] > arr[j + 1]:
07 arr[j], arr[j + 1] = arr[j + 1], arr[j]
08
09 # Example usage:
10 arr = [64, 34, 25, 12, 22, 11, 90]
11 print("The Given array is:", arr)
12 bubble_sort(arr)
13 print("Sorted array is:", arr)

26
OUTPUT:

RESULT:

Thus, the program is to sort a list of numbers using the bubble sort algorithm is
completed successfully

27
Exp No: 14
Word Count
Date :

AIM:
The aim of this program is to count the occurrences of each word in a given
text.

ALGORITHM:
Step-1. Given a string of text.
Step-2. Split the text into words using spaces as delimiters.
Step-3. Create an empty dictionary to hold the word counts.
Step-4. Iterate through each word in the list:
Step-5. If the word is already in the dictionary, increment its count.
Step-6. If the word is not in the dictionary, add it with a count of 1.
Step-7. Return the dictionary with word counts.
PROGRAM:
01 # A Python Program for Word Count
02 def word_count(text):
03 words = text.split()
04 word_counts = {}
05
06 for word in words:
07 word = word.lower() # Optional: Normalize to lowercase
08 if word in word_counts:
09 word_counts[word] += 1
10 else:
11 word_counts[word] = 1
12
13 return word_counts
14
15 # Example usage:
16 text = "This is a test. This test is only a test."
17 print("The Given Text :", text)
18 result = word_count(text)
19
20 print("Word Counts: ", result)

28
OUTPUT:

RESULT:

Thus, the program is to count the occurrences of each word in a given text is
completed successfully

29
Exp No: 15
Copy File
Date :

AIM:
The aim of this task is to create a Python program that copies the contents of
one file to another using an algorithm that reads the content from the source
file and writes it to the destination file.

ALGORITHM:
Step-1. Open the Source File: Open the file that you want to copy from in
read mode.
Step-2. Read the Contents: Read the content of the source file.
Step-3. Open/Create the Destination File: Open the file that you want to copy
to in write mode. If the file does not exist, it will be created.
Step-4. Write the Contents: Write the content read from the source file to the
destination file.
Step-5. Close Both Files: Close both the source and destination files to
ensure all data is properly written and resources are released.

30
PROGRAM:
01 # A Python Program to Copy a File
02 def copy_file(source_file, destination_file):
03 try:
04 # Open the source file in read mode
05 with open(source_file, 'r') as src:
06 # Read the content from the source file
07 content = src.read()
08
09 # Open the destination file in write mode
10 with open(destination_file, 'w') as dst:
11 # Write the content to the destination file
12 dst.write(content)
13
14 print(f"File copied successfully from {source_file} to
{destination_file}.")
15 except FileNotFoundError:
16 print(f"Error: The file {source_file} does not exist.")
17 except IOError as e:
18 print(f"An I/O error occurred: {e}")
19
20 # Example usage
21 source_file = 'Exp-15.py'
22 destination_file = 'destination.txt'
23 copy_file(source_file, destination_file)
24

31
OUTPUT:

RESULT:

Thus, copy operation is demonstrated successfully

32
Exp No: 16
VOTER’S AGE VALIDATION
Date :

AIM:
The aim of this task is to create a Python program that validates whether a
person is eligible to vote based on their age. The typical voting age is 18 years
and older. The program will take the person's birth year as input, calculate
their age, and determine if they are eligible to vote.

ALGORITHM:
Step-1. Input the Birth Year: Prompt the user to enter their birth year.
Step-2. Calculate the Current Year: Get the current year from the system.
Step-3. Calculate the Age: Subtract the birth year from the current year to
determine the person's age.
Step-4. Check Eligibility:
Step-5. If the age is 18 or older, the person is eligible to vote.
Step-6. If the age is less than 18, the person is not eligible to vote.
Step-7. Display the Result: Print a message indicating whether the person is
eligible to vote or not.

33
PROGRAM:
01 # A Python Program to Validate Age of Voter From YOB
02 from datetime import datetime
03
04 def is_eligible_to_vote(birth_year):
05 current_year = datetime.now().year
06 age = current_year - birth_year
07
08 if age >= 18:
09 return True, age
10 else:
11 return False, age
12
13 def main():
14 try:
15 birth_year = int(input("Enter your year of birth: "))
16 eligible, age = is_eligible_to_vote(birth_year)
17
18 if eligible:
19 print(f"You are {age} years old. You are eligible to vote.")
20 else:
21 print(f"You are {age} years old. You are not eligible to vote.")
22 except ValueError:
23 print("Invalid input. Please enter a valid year.")
24
25 if __name__ == "__main__":
26 main()

34
OUTPUT:

RESULT:

Thus, voters age validation program is completed successfully

35
Exp No: 17
MARKS RANGE VALIDATION
Date :

AIM:
The aim of this task is to create a Python program that validates whether a
given mark falls within a specified range. Typically, marks are expected to be
within the range of 0 to 100. The program will take the mark as input and
determine if it is valid based on this range.

ALGORITHM:
Step-1. Input the Mark: Prompt the user to enter their mark.
Step-2. Check if the Mark is a Number: Validate that the input is a number.
Step-3. Validate the Mark:
Step-4. If the mark is within the range of 0 to 100, it is valid.
Step-5. If the mark is outside this range, it is invalid.
Step-6. Display the Result: Print a message indicating whether the mark is
valid or not.

36
PROGRAM:
01 # A Python Program to Validate Marks
02 def is_valid_mark(mark):
03 # Check if the mark is within the valid range
04 return 0 <= mark <= 100
05
06 def main():
07 try:
08 # Prompt the user to enter their mark
09 mark = float(input("Enter your mark: "))
10
11 # Validate the mark
12 if is_valid_mark(mark):
13 print(f"The mark {mark} is valid.")
14 else:
15 print(f"The mark {mark} is invalid. Marks should be between 0
and 100.")
16 except ValueError:
17 print("Invalid input. Please enter a numeric value.")
18
19 if __name__ == "__main__":
20 main()

37
`
OUTPUT:

RESULT:

Thus, Mark validation program is completed successfully

38

You might also like