0% found this document useful (0 votes)
8 views91 pages

CS LAb Record

Uploaded by

RAM K SHIVANY
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)
8 views91 pages

CS LAb Record

Uploaded by

RAM K SHIVANY
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/ 91

Ex.

No: 1 - Basic Python Programs

1.1-Write a program to determine the gcd of a number.

AIM:
To write a program to determine the gcd of a number.

ALGORITHM:

1. Input: Take two positive integers, a and b.


2. Initialize: Set two variables, x and y, where x is the larger of the two numbers and y is the
smaller.
3. Divide: Divide x by y and get the remainder (r).
4. Swap: Set x = y and y = r.
5. Repeat: Repeat steps 3 and 4 until y becomes 0.
6. Output: The GCD is the non-zero remainder obtained in the last iteration.

PROGRAM:

def gcd(a,b):

if(b==0):

return a

else:

return gcd(b,a%b)

a=int(input("Enter first number:"))

b=int(input("Enter second number:"))

GCD=gcd(a,b)

print("GCD is: ")

print(GCD)
OUTPUT:

GOOGLE COLAB REFERENCE LINK:

Python.ipynb

RESULT:
Thus, python program is successfully implemented that determines the gcd of a number.
1.2-Write a program to determine the square root of a number.

AIM:
To write a program to determine the square root of a number.

ALGORITHM:
1. Import the math module.
2. Take user input for the number.
3. Use the sqrt function from the math module to calculate the square root.
4. Display the result.
5. End.

PROGRAM:
import math
n=int(input('Enter a number'))
print(math.sqrt(n))

OUTPUT:

GOOGLE COLAB REFERENCE LINK:

Python.ipynb

RESULT:
Thus, python program is successfully implemented that determines the square root of a
number.
1.3-Write a program to determine the exponentiation of a number.

AIM:
To write a program to determine the exponentiation of a number.

ALGORITHM:
1. Input: Obtain the base (the number to be raised) and the exponent (the power).
2. Initialize Result: Set a variable to 1 to store the result.
3. Loop: Multiply the result by the base for each iteration, reducing the exponent by 1 until
the exponent becomes 0.
4. Output: The final result is the exponentiation of the given number.
5. End.

PROGRAM:
import math
ex=int(input('Enter a number'))
print("Exponential Value is: ", math.exp(ex))

OUTPUT:

GOOGLE COLAB REFERENCE LINK:

Python.ipynb

RESULT:
Thus, python program is successfully implemented that determines the exponentiation of
a number.
1.4-Write a program to determine the first n prime numbers

AIM:
To write a program to determine the first n prime numbers

ALGORITHM:
1. Initialize an empty list to store prime numbers.
2. Start with the first number (2) and iterate until you have n primes.
3. For each number, check divisibility by all previous primes.
4. If not divisible, add it to the list of primes.
5. Repeat until you have n primes.
6. End.

PROGRAM:
def isPrime(n):
if(n==1 or n==0):
return False
for i in range(2,n):
if(n%i==0):
return False
return True

n=int (input('Enter a number:'))


for i in range(1,n+1):
if(isPrime(i)):
print(i,end=' ')
OUTPUT:

GOOGLE COLAB REFERENCE LINK:

Python.ipynb

RESULT:
Thus, python program is successfully implemented that determines the first n prime
numbers.
1.5-Write a program to determine the Fibonacci series.

AIM:
To write a program to determine the Fibonacci series.

ALGORITHM:
1. Set the first two numbers as 0 and 1.
2. Iterate by adding the previous two numbers to generate the next one.
3. Repeat the process until reaching the desired length or condition.
4. The sequence starts as 0, 1, 1, 2, 3, 5, 8, 13, and so on.
5. The nth Fibonacci number is the sum of the (n-1)th and (n-2)th numbers.
6. Continue this process to extend the series.
7. End

PROGRAM:
N=int(input('Enter a number:'))
a,b=0,1
for _ in range(N):
print(a)
temp=a+b
a=temp
b=temp

OUTPUT:
GOOGLE COLAB REFERENCE LINK:

Python.ipynb

RESULT:
Thus, python program is successfully implemented that determines the Fibonacci series.
Ex.No:2 - Programs using Branching statements

2.1 -Write a program to determine whether a person is eligible to vote or not. if the person
is not eligible, display how many years are left to be eligible.

AIM :
To Write a program to determine whether a person is eligible to vote or not. if the person
is not eligible, display how many years are left to be eligible.

ALGORITHM:

1. Input: Person's age (age) and minimum voting age (min_age).


2. Check eligibility: If age >= min_age, then eligible.
3. Calculate years left: If ineligible, years_left = min_age - age.
4. Output: Print "Eligible to vote!" if eligible.
5. Otherwise, print "Not eligible, %d years left" with years_left.
6. End: Repeat process for any additional person (optional).
7. Exit: End program.

PROGRAM :

def is_eligible_to_vote(current_age, voting_age):


if current_age >= voting_age:
print("You are eligible to vote!")
else:
years_left = voting_age - current_age
print(f"You are not eligible to vote yet. You need to wait {years_left} more years.")

current_age = int(input("Enter the age:"))


voting_age = 18
is_eligible_to_vote(current_age, voting_age)
OUTPUT :

GOOGLE COLAB REFERENCE LINK:

Python.ipynb

RESULT:
Thus, python program is successfully implemented that checks whether a person is
eligible to vote or not.
2.2 - Write a program that prompts the user to enter a number between 1-7 and then
displays the corresponding day of the week.

AIM :
To write a program that prompts the user to enter a number between 1-7 and then displays
the corresponding day of the week.

ALGORITHM :
1. Prompt User: Ask the user to enter a number between 1 and 7.
2. Get Input: Read the user's input as a string.
3. Check Validity: Check if the input is a valid integer using isdigit().
4. Convert to Integer: If valid, convert the input to an integer.
5. Check Range: Verify that the integer is between 1 and 7 (inclusive).
6. Display Day: If within range, display the corresponding day of the week using a list.
7. Invalid Input Handling: If not valid or out of range, print an appropriate error message.
8. End.

PROGRAM :

user_input = input("Enter a number between 1 and 7: ")


if user_input.isdigit():
day_number = int(user_input)
if 1 <= day_number <= 7:
days_of_week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
"Saturday", "Sunday"]
selected_day = days_of_week[day_number - 1]
print(f"The corresponding day of the week is {selected_day}.")
else:
print("Invalid input. Please enter a number between 1 and 7.")
else:
print("Invalid input. Please enter a valid integer.")
OUTPUT :

GOOGLE COLAB REFERENCE LINK:

Python.ipynb

RESULT :
Thus, python program is successfully implemented that prompts the user to enter a
number between 1-7 and then displays the corresponding day of the week.
2.3 - Write a program to take input from the user and then check whether it is a number or
a character, determine whether it is in uppercase or lowercase.

AIM :
To write a program to take input from the user and then check whether it is a number or a
character, determine whether it is in uppercase or lowercase.

ALGORITHM:
1. Prompt User: Ask the user to enter a character or a number.
2. Get Input: Read the user's input as a string.
3. Check Number: Use isdigit() to check if the input is a number.
4. Check Character: Use isalpha() to check if the input is a character.
5. Determine Case: If it's a character, use islower() and isupper() to determine if it's in
lowercase or uppercase.
6. Display Results: Print whether the input is a number, a character, and its case (if
applicable).
7. Invalid Input Handling: If the input is neither a number nor a character, print an error
message.
8. End.

PROGRAM :

user_input = input("Enter a character or a number: ")


if user_input.isdigit():
print("The input is a number.")
elif user_input.isalpha():
print("The input is a character.")
if user_input.islower():
print("The character is in lowercase.")
elif user_input.isupper():
print("The character is in uppercase.")
else:
print("The character is not entirely uppercase or lowercase.")
else:
print("Invalid input. Please enter either a character or a number.")
OUTPUT:

GOOGLE COLAB REFERENCE LINK:

Python.ipynb

RESULT:
Thus, python program is successfully implemented that take input from the user and then
check whether it is a number or a character, determine whether it is in uppercase or lowercase.
Ex.No:3 - Programs on strings

3.1 -Program to demonstrate the slice operation on string objects(use negative indexes also)

AIM:
To demonstrate the slice operation on string objects(use negative indexes also)

ALGORITHM:
1. Initialize String: Create a sample string, e.g., "Hello, World!".
2. Positive Slicing: Use positive indexes to extract a substring, e.g., original_string[7:12].
3. Negative Slicing: Use negative indexes to extract another substring, e.g.,
original_string[-6:-1].
4. Slicing with a Step: Use a step value to extract characters at intervals, e.g.,
original_string[::2].
5. Reverse String: Use negative step to reverse the string, e.g., original_string[::-1].
6. Display Results: Print the results of each slicing operation.
7. End.

PROGRAM:

# Sample string
original_string =input("Enter the string : ")

# Positive slicing
substring_pos = original_string[7:12]
print(f"Positive slicing: {substring_pos}")

# Negative slicing
substring_neg = original_string[-6:-1]
print(f"Negative slicing: {substring_neg}")

# Slicing with a step


substring_step = original_string[::2]
print(f"Slicing with a step: {substring_step}")

# Reverse the string


reverse_string = original_string[::-1]
print(f"Reversed string: {reverse_string}")
OUTPUT:

GOOGLE COLAB REFERENCE LINK :

Python.ipynb

RESULT:
Thus, python program is successfully implemented that demonstrate the slice operation
on string objects.
3.2- Write a program that accepts string from user and redisplays the same string after
removing vowels from it.

AIM:
To write a program that accepts string from user and redisplays the same string after
removing vowels from it.

ALGORITHM :
1. Initialize Vowels String: Create a string containing all vowels, e.g., "aeiouAEIOU".
2. Function to Remove Vowels: Define a function that takes a string and removes vowels
using a list comprehension.
3. Get User Input: Prompt the user to enter a string.
4. Remove Vowels: Call the function with the user's input to remove vowels.
5. Display Result: Print the modified string without vowels.
6. End.

PROGRAM:

def remove_vowels(input_string):
vowels = "aeiouAEIOU"
result_string = ''.join(char for char in input_string if char not in vowels)
return result_string

# Get string input from the user


user_input = input("Enter a string: ")

# Remove vowels and display the result


result = remove_vowels(user_input)
print(f"String after removing vowels: {result}")
OUTPUT:

GOOGLE COLAB REFERENCE LINK:

Python.ipynb

RESULT :
Thus, python program is successfully implemented that accepts string from user and
redisplays the same string after removing vowels from it.
3.3- Write a program that counts the occurences of a character in a string. Do not use
built-in count function.

AIM :
To write a program that counts the occurences of a character in a string. Do not use
built-in count function.

ALGORITHM :
1. Initialize Counter: Create a variable count and set it to 0.
2. Define Function: Create a function that takes a string and a target character.
3. Iterate Through String: Use a loop to iterate through each character in the string.
4. Check for Match: If the character matches the target character, increment the counter.
5. Get User Input: Prompt the user to enter a string and a target character.
6. Check Target Length: Ensure the target is a single character.
7. Count Occurrences: Call the function to count occurrences and display the result.
8. End.

PROGRAM :

def count_occurrences(input_string, target_character):


count = 0
for char in input_string:
if char == target_character:
count += 1
return count

# Get string and character input from the user


user_input = input("Enter a string: ")
target_char = input("Enter the character to count: ")

# Check if a single character is entered as target


if len(target_char) == 1:
# Count occurrences and display the result
occurrences = count_occurrences(user_input, target_char)
print(f"The character '{target_char}' occurs {occurrences} times in the string.")
else:
print("Please enter a single character as the target.")
OUTPUT:

GOOGLE COLAB REFERENCE LINK:

Python.ipynb

RESULT:
Thus, python program is successfully implemented that counts the occurences of a
character in a string. Do not use built-in count function.
3.4- Write a python program to count the occurences of each word in a given sentence.

AIM:
To write a python program to count the occurences of each word in a given sentence.

ALGORITHM:

1. Initialize Word Count Dictionary: Create an empty dictionary word_count to store word
occurrences.
2. Split Sentence into Words: Use the split method to break the sentence into a list of words.
3. Iterate Through Words: Loop through each word in the list.
4. Remove Punctuation and Convert to Lowercase: Strip punctuation and convert each word
to lowercase for consistency.
5. Update Word Count Dictionary: Update the dictionary, incrementing the count for each
word.
6. Get User Input: Prompt the user to enter a sentence.
7. Count Word Occurrences: Call the function to count word occurrences and store the
result in result.
8. Display Result: Print the word occurrences in the sentence.
9. End.

PROGRAM:

def count_word_occurrences(sentence):
word_count = {}
words = sentence.split()

for word in words:


# Remove punctuation (if any) from the word
word = word.strip(".,!?")

# Convert the word to lowercase for case-insensitive counting


word = word.lower()

# Update the word count dictionary


if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
return word_count

# Get input sentence from the user


user_sentence = input("Enter a sentence: ")

# Count word occurrences and display the result


result = count_word_occurrences(user_sentence)
print("Word occurrences in the sentence:")
for word, count in result.items():
print(f"{word}: {count}")

OUTPUT:
GOOGLE COLAB REFERENCE LINK:

Python.ipynb

RESULT:
Thus, python program is successfully implemented that counts the occurences of each
word in a given sentence.
3.5- Write a program by adding a key value to every character(Hint: if key=5, then add 5
to every character)

AIM:
To write a program by adding a key value to every character(Hint: if key=5, then add 5 to
every character)

ALGORITHM:
1. Initialize Result String: Create an empty string result_string to store the modified
characters.
2. Iterate Through Characters: Loop through each character in the input string.
3. Check if Alphabet Letter: Use isalpha() to determine if the character is an alphabet letter.
4. Determine Case and Add Key: If it's an alphabet letter, determine its case (uppercase or
lowercase) and add the key value.
5. Use ord() to get the ASCII value, add the key, and use chr() to convert it back to a
character.
6. Apply modulo 26 to handle wrapping around the alphabet.
7. Keep Non-Alphabetic Characters Unchanged: If not an alphabet letter, keep the character
unchanged.
8. Get User Input: Prompt the user to enter a string and a key value.
9. Add Key to Characters: Call the function to add the key value to characters and store the
result in result.
10. Display Result: Print the modified result after adding the key to characters.
11. End.

PROGRAM:
def add_key_to_characters(input_string, key):
result_string = ""
for char in input_string:
# Check if the character is an alphabet letter
if char.isalpha():
# Determine the case (uppercase or lowercase) and add the key
if char.islower():
result_string += chr((ord(char) - ord('a') + key) % 26 + ord('a'))
else:
result_string += chr((ord(char) - ord('A') + key) % 26 + ord('A'))
else:
# If not an alphabet letter, keep the character unchanged
result_string += char
return result_string
# Get input string and key from the user
user_input = input("Enter a string: ")
key = int(input("Enter the key value: "))

# Add key to characters and display the result


result = add_key_to_characters(user_input, key)
print(f"Result after adding key {key} to characters: {result}")

OUTPUT:

GOOGLE COLAB REFERENCE LINK:

Python.ipynb

RESULT:
Thus, python program is successfully implemented that add a key value to every
character
3.6 - Write a program that finds whether a given character is present in a string or not.

AIM:
To write a program that finds whether a given character is present in a string or not.

ALGORITHM:
1. Initialize Flag: Create a boolean variable found and set it to False.
2. Iterate Through Characters: Loop through each character in the input string.
3. Check for Match: If the character matches the target character, set found to True and
break the loop.
4. Get User Input: Prompt the user to enter a string and a target character.
5. Check Character Presence: Call the function to check whether the character is present and
store the result in result.
6. Display Result: Print whether the character is present or not based on the value of result.
7. End.

PROGRAM:

def is_character_present(input_string, target_character):


for char in input_string:
if char == target_character:
return True
return False

# Get input string and character from the user


user_input = input("Enter a string: ")
target_char = input("Enter the character to check: ")

# Check if the character is present and display the result


result = is_character_present(user_input, target_char)
if result:
print(f"The character '{target_char}' is present in the string.")
else:
print(f"The character '{target_char}' is not present in the string.")
OUTPUT:

GOOGLE COLAB REFERENCE LINK:

Python.ipynb

RESULT:
Thus, python program is successfully implemented that finds whether a given character is
present in a string or not.
Ex.No:4 - Programs using functions

4.1 - Write a function called fizz_buzz that takes a number.


1. If the number is divisible by 3, it should return “Fizz”.
2. If it is divisible by 5, it should return “Buzz”.
3. If it is divisible by both 3 and 5, it should return “FizzBuzz”.
4. Otherwise, it should return the same number.

AIM:
To write a function called fizz_buzz that takes a number and returns “Fizz” , “Buzz” ,
“FizzBuzz” , “Number” based on the input given.

ALGORITHM:
1. Define Function fizz_buzz: Create a function that takes a number as input.
2. Check Divisibility by 3 and 5: If the number is divisible by both 3 and 5, return
"FizzBuzz".
3. Check Divisibility by 3: If the number is divisible by 3, return "Fizz".
4. Check Divisibility by 5: If the number is divisible by 5, return "Buzz".
5. Default Case: If none of the above conditions are met, return the original number.
6. Get User Input: Prompt the user to enter a number.
7. Call Function and Display Result: Call the function with the user's input and print the
result.
8. End.

PROGRAM:
def fizz_buzz(number):
if number % 3 == 0 and number % 5 == 0:
return "FizzBuzz"
elif number % 3 == 0:
return "Fizz"
elif number % 5 == 0:
return "Buzz"
else:
return number
# Get input number from the user
user_number = int(input("Enter a number: "))

# Call the function and display the result


result = fizz_buzz(user_number)
print(f"The result for {user_number} is: {result}")
OUTPUT:

GOOGLE COLAB REFERENCE LINK:

Python.ipynb

RESULT:
Thus, python program is successfully implemented that takes a number and returns
“Fizz” , “Buzz” , “FizzBuzz” , “Number” based on the input given.
4.2 - Write a function for checking the speed of drivers. This function should have one
parameter: speed.

1. If speed is less than 70, it should print “Ok”.


2. Otherwise, for every 5 km above the speed limit (70), it should give the driver one
demerit point and print the total number of demerit points.
For example, if the speed is 80, it should print: “Points: 2”.
3. If the driver gets more than 12 points, the function should print: “License suspended”

AIM:
To write a function for checking the speed of drivers and print the desired output.

ALGORITHM:
1. Define Function check_speed: Create a function that takes the speed as input.
2. Set Speed Limit and Demerit Points: Initialize the speed limit to 70 and demerit points to
0.
3. Check Speed Against Limit:
4. a. If the speed is less than 70, print "Ok".
5. b. If the speed is greater than or equal to 70, calculate demerit points based on the
formula: (speed - speed_limit) // 5.
6. Display Demerit Points: Print the number of demerit points.
7. Check License Suspension: If the demerit points exceed 12, print "License suspended".
8. Get User Input: Prompt the user to enter the speed.
9. Call Function and Display Result: Call the function with the user's input and print the
result.
10. End.

PROGRAM:
def check_speed(speed):
speed_limit = 70
demerit_points = 0

if speed < speed_limit:


print("Ok")
else:
demerit_points = (speed - speed_limit) // 5
print(f"Points: {demerit_points}")

if demerit_points > 12:


print("License suspended")
# Get input speed from the user
user_speed = int(input("Enter the speed: "))

# Call the function and display the result


check_speed(user_speed)

OUTPUT:

GOOGLE COLAB REFERENCE LINK:

Python.ipynb

RESULT:
Thus, python program is successfully implemented that checks the speed of drivers and
print the desired output.
4.3 - Write a program using function to calculate simple interest. Suppose the customer is a
senior citizen. He is being offered 12 percent rate of interest; for all other customers, the
rate of interest is 10 percent.

AIM:
To write a program using function to calculate simple interest.

ALGORITHM:
1. Create a function that takes principal amount, time, and a flag for senior citizen status as
input.
2. Set Interest Rate:If the customer is a senior citizen, set the interest rate to 12%; otherwise,
set it to 10%.
3. Calculate Simple Interest:Use the formula (principal * rate * time) / 100 to calculate
simple interest.
4. Get User Input:Prompt the user to enter the principal amount, time period, and whether
they are a senior citizen.
5. Call Function and Display Result:Call the function with the user's input and print the
calculated simple interest.
6. End.

PROGRAM:
def calculate_simple_interest(principal, time, senior_citizen=False):
if senior_citizen:
rate_of_interest = 0.12
else:
rate_of_interest = 0.10

interest = (principal * rate_of_interest * time) / 100


return interest

# Get input from the user


principal_amount = float(input("Enter the principal amount: "))
time_period = float(input("Enter the time period (in years): "))
is_senior_citizen = input("Are you a senior citizen? (yes/no): ").lower() == "yes"

# Call the function and display the result


interest_amount = calculate_simple_interest(principal_amount, time_period,
is_senior_citizen)
print(f"The simple interest is: {interest_amount}")
OUTPUT:

GOOGLE COLAB REFERENCE LINK:

Python.ipynb

RESULT:
Thus, python program is successfully implemented that calculates simple interest.
Ex.No:5 - Program on Lists

5.1- Write a program that asks the user to enter a list of integers. Do the following:
(a) Print the total number of items in the list.
(b) Print the last item in the list.
(c) Print the list in reverse order.
(d) Print Yes if the list contains a 5 and No otherwise.
(e) Print the number of fives in the list.
(f) Remove the first and last items from the list, sort the remaining items, and print the
result .
(g) Print how many integers in the list are less than 5.

AIM:
To write a program that asks the user to enter a list of integers and print the desired
output.

ALGORITHM:
1. Get the user to enter a list of integers, converting the input into a list.
2. Print the total number of items in the list.
3. Print the last item in the list.
4. Print the list in reverse order.
5. Print "Yes" if the list contains a 5, otherwise "No".
6. Print the number of occurrences of 5 in the list.
7. Remove the first and last items, sort the remaining items, and print the result.
8. Print the number of integers in the list that are less than 5.
9. End.

PROGRAM:
integer_list = [int(x) for x in input("Enter a list of integers separated by spaces: ").split()]
# (a) Print the total number of items in the list
print(f"Total number of items in the list: {len(integer_list)}")

# (b) Print the last item in the list


print(f"Last item in the list: {integer_list[-1]}")

# (c) Print the list in reverse order


print(f"List in reverse order: {integer_list[::-1]}")

# (d) Print Yes if the list contains a 5 and No otherwise


print(f"Contains a 5: {'Yes' if 5 in integer_list else 'No'}")
# (e) Print the number of fives in the list
print(f"Number of fives in the list: {integer_list.count(5)}")

if len(integer_list) >= 2:
integer_list.pop(0)
integer_list.pop()
integer_list.sort()
print(f"List after removing first and last items, and sorting: {integer_list}")
else:
print("List has fewer than 2 items.")

count_less_than_5 = sum(1 for num in integer_list if num < 5)


print(f"Number of integers less than 5: {count_less_than_5}")

OUTPUT:
GOOGLE COLAB REFERENCE LINK:

Python.ipynb

RESULT:
Thus, python program is successfully implemented that asks the user to enter a list of
integers and print the desired output.
5.2- Write a program that generates a list of 20 random numbers between 1 and 100.
(a) Print the list.
(b) Print the average of the elements in the list.
(c) Print the largest and smallest values in the list.
(d) Print the second largest and second smallest entries in the list
(e) Print how many even numbers are in the list.

AIM:
To write a program that generates a list of 20 random numbers between 1 and 100 and
print the desired output.

ALGORITHM:
1. Generate a list of 20 random numbers between 1 and 100.
2. Print the generated list.
3. Calculate and print the average of the list elements.
4. Find and print the largest and smallest values in the list.
5. Sort the list and print the second largest and second smallest entries.
6. Count and print how many even numbers are in the list.
7. End

PROGRAM:
import random

# Generate a list of 20 random numbers between 1 and 100


random_numbers = [random.randint(1, 100) for _ in range(20)]

# (a) Print the list


print("List of random numbers:", random_numbers)

# (b) Print the average of the elements in the list


average = sum(random_numbers) / len(random_numbers)
print(f"Average of the elements: {average}")

# (c) Print the largest and smallest values in the list


largest_value = max(random_numbers)
smallest_value = min(random_numbers)
print(f"Largest value: {largest_value}, Smallest value: {smallest_value}")

# (d) Print the second largest and second smallest entries in the list
sorted_numbers = sorted(random_numbers)
second_largest = sorted_numbers[-2]
second_smallest = sorted_numbers[1]
print(f"Second largest value: {second_largest}, Second smallest value:
{second_smallest}")

# (e) Print how many even numbers are in the list


even_count = sum(1 for num in random_numbers if num % 2 == 0)
print(f"Number of even numbers: {even_count}")

OUTPUT:
GOOGLE COLAB REFERENCE LINK:

Python.ipynb

RESULT:
Thus, python program is successfully implemented that generates a list of 20 random
numbers between 1 and 100 and print the desired output.
5.3- Start with the list [8,9,10]. Do the following:
(a) Set the second entry (index 1) to 17
(b) Add 4, 5, and 6 to the end of the list
(c) Remove the first entry from the list
(d) Sort the list
(e) Double the list
(f) Insert 25 at index 3.
The final list should equal [4,5,6,25,10,17,4,5,6,10,17]

AIM:
To start with the list [8,9,10] and do the given operations and print the desired output.

ALGORITHM:
1. Initialize the list as [8, 9, 10].
2. Set the second entry (index 1) to 17.
3. Add 4, 5, and 6 to the end of the list.
4. Remove the first entry from the list.
5. Sort the list.
6. Double the list.
7. Insert 25 at index 3.
8. Print the final list.
9. End.

PROGRAM:
# Start with the list [8, 9, 10]
my_list = [8, 9, 10]

# (a) Set the second entry (index 1) to 17


my_list[1] = 17

# (b) Add 4, 5, and 6 to the end of the list


my_list.extend([4, 5, 6])

# (c) Remove the first entry from the list


my_list.pop(0)

# (d) Sort the list


my_list.sort()

# (e) Double the list


my_list *= 2

# (f) Insert 25 at index 3


my_list.insert(3, 25)

# Print the final list


print("The final list:", my_list)

OUTPUT:

GOOGLE COLAB REFERENCE LINK:

Python.ipynb

RESULT:
Thus, python program is successfully implemented that the given operations are
performed and the desired output is printed.
Ex.No:6 - Programs on Tuples

6.1- Write a program that has a list of numbers (both positive as well as negative). Make a
new tuple that has only positive values from this list.

AIM:
To write a program that has a list of numbers (both positive as well as negative). Make a
new tuple that has only positive values from this list.

ALGORITHM:
1. Initialize a list of numbers containing both positive and negative values.
2. Create a new tuple by using a generator expression to include only positive values from the list.
3. Print the original list of numbers and the tuple with positive values.
4. End.

PROGRAM:
# Sample list of numbers (positive and negative)
number_list = [10, -5, 8, -3, 15, -7, 20, -1]

# Create a new tuple with only positive values


positive_numbers_tuple = tuple(num for num in number_list if num > 0)

# Print the original list and the tuple with positive values
print("Original list of numbers:", number_list)
print("Tuple with positive values:", positive_numbers_tuple)

OUTPUT:
GOOGLE COLAB REFERENCE LINK:

Python.ipynb

RESULT:
Thus, python program is successfully implemented that has a list of numbers (both
positive as well as negative) and made a new tuple that has only positive values from this list.
6.2- Write a program that accepts different number of arguments and return sum of only
the positive values passed to it.

AIM:
To write a program that accepts different number of arguments and return sum of only the
positive values passed to it.

ALGORITHM:
1. Define a function sum_positive_values that accepts a variable number of arguments
(*args).
2. Use a generator expression within the function to sum only the positive values among the
provided arguments.
3. Call the function with different numbers.
4. Print the result.
5. End.

PROGRAM:
def sum_positive_values(*args):
return sum(num for num in args if num > 0)

# Example usage:
result = sum_positive_values(5, -3, 10, -2, 7)
print(f"Sum of positive values: {result}")

OUTPUT:
GOOGLE COLAB REFERENCE LINK:

Python.ipynb

RESULT:
Thus, python program is successfully implemented that accepts different number of
arguments and return sum of only the positive values passed to it.
6.3- Write a program that has two sequences. First which stores some questions and second
stores the corresponding answers. use the zip() function to form a valid question answer
series.

AIM:
To write a program that has two sequences. First which stores some questions and second
stores the corresponding answers. use the zip() function to form a valid question answer series

ALGORITHM:
1. Initialize two sequences, one for questions and one for answers.
2. Use the zip() function to combine the questions and answers into pairs, forming a
question-answer series.
3. Iterate through the resulting series.
4. Print each question and its corresponding answer.
5. End.

PROGRAM:

questions = ["What is your name?", "Where are you from?", "What is your favorite
color?"]
answers = ["My name is John.", "I am from New York.", "My favorite color is blue."]

# Use zip() to form a question-answer series


question_answer_series = zip(questions, answers)

# Print the resulting series


print("Question-Answer Series:")
for question, answer in question_answer_series:
print(f”Q: {question}\nA: {answer}\n")
OUTPUT:

GOOGLE COLAB REFERENCE LINK:

Python.ipynb

RESULT:
Thus, python program is successfully implemented that has two sequences. First which
stores some questions and second stores the corresponding answers using the zip() function to
form a valid question answer series
Ex.No 7: Programs on Sets and dictionaries

7.1 : Write a program that generates a set of prime numbers and another set of odd
numbers. Demonstrate the result of union, intersection, difference and symmetric
difference operations on these sets.

AIM:
To write a program that generates a set of prime numbers and another set of odd numbers.
Demonstrate the result of union, intersection, difference and symmetric difference operations on
these sets.

ALGORITHM:
1. Define a function is_prime to check if a given number is prime.
2. Generate sets of prime numbers and odd numbers using list comprehensions.
3. Print the sets of prime numbers and odd numbers.
4. Perform set operations:
a. Union: union_result = prime_numbers.union(odd_numbers)
b. Intersection: intersection_result = prime_numbers.intersection(odd_numbers)
c. Difference: difference_result = prime_numbers.difference(odd_numbers)
d. Symmetric Difference: symmetric_difference_result =
prime_numbers.symmetric_difference(odd_numbers)
5. Print the results of each set operation.
6. End.

PROGRAM:
def is_prime(number):
if number < 2:
return False
for i in range(2, int(number**0.5) + 1):
if number % i == 0:
return False
return True

# Generate sets of prime numbers and odd numbers


prime_numbers = {num for num in range(30) if is_prime(num)}
odd_numbers = set(range(1, 20, 2))

# Demonstrate set operations


print("Set of Prime Numbers:", prime_numbers)
print("Set of Odd Numbers:", odd_numbers)
# Union of sets
union_result = prime_numbers.union(odd_numbers)
print("Union of sets:", union_result)

# Intersection of sets
intersection_result = prime_numbers.intersection(odd_numbers)
print("Intersection of sets:", intersection_result)

# Difference of sets
difference_result = prime_numbers.difference(odd_numbers)
print("Difference of sets (Prime - Odd):", difference_result)

# Symmetric difference of sets


symmetric_difference_result = prime_numbers.symmetric_difference(odd_numbers)
print("Symmetric Difference of sets:", symmetric_difference_result)

OUTPUT:
GOOGLE COLAB REFERENCE LINK:

Python.ipynb

RESULT:
Thus, python program is successfully implemented that generates a set of prime numbers
and another set of odd numbers and also demonstration of the result of union, intersection,
difference and symmetric difference operations on these sets is done.
7.2 : Write a program that has a dictionary of names of students and a list of their marks in
4 subjects. Create another dictionary from this dictionary that has the name of the students
and their total marks. Find out the topper and his/her score.

AIM:
To write a program that has a dictionary of names of students and a list of their marks in
4 subjects and another dictionary from this dictionary that has the name of the students and their
total marks. Find out the topper and his/her score.

ALGORITHM:
1. Create a dictionary (student_marks) with names of students as keys and lists of their
marks in 4 subjects as values.
2. Generate a new dictionary (total_marks_dict) with names of students and their total
marks calculated using a list comprehension.
3. Find the topper in the total_marks_dict using max and key arguments.
4. Retrieve the score of the topper from total_marks_dict.
5. Print the original dictionary (student_marks), total marks dictionary (total_marks_dict),
and the topper along with their score.
6. End.

PROGRAM:
# Sample dictionary of students and their marks
student_marks = {
"John": [85, 90, 88, 92],
"Alice": [78, 95, 89, 87],
"Bob": [92, 88, 95, 78],
"Eve": [80, 85, 90, 88]
}

# Create a dictionary with the name and total marks for each student
total_marks_dict = {name: sum(marks) for name, marks in student_marks.items()}

# Find the topper and their score


topper = max(total_marks_dict, key=total_marks_dict.get)
topper_score = total_marks_dict[topper]

# Print the original dictionary, total marks dictionary, and the topper with their score
print("Original Dictionary of Student Marks:")
print(student_marks)
print("\nTotal Marks Dictionary:")
print(total_marks_dict)

print("\nTopper:")
print(f"Name: {topper}, Score: {topper_score}")

OUTPUT:

GOOGLE COLAB REFERENCE LINK:

Python.ipynb

RESULT:
Thus, python program is successfully implemented that has a dictionary of names of
students and a list of their marks in 4 subjects and another dictionary that has the name of the
students and their total marks.
7.3 : Write a program that has a set of words in English language and their corresponding
words in German. Define another dictionary that has a list of words in German and their
corresponding words in French. Take all words from English language and display their
meanings in both the languages.

AIM:
To write a program that has a set of words in English language and their corresponding
words in German using dictionaries.

ALGORITHM:
1. Define a dictionary (english_to_german) with English words as keys and their
corresponding words in German as values.
2. Define another dictionary (german_to_french) with German words as keys and their
corresponding words in French as values.
3. Iterate through the English words in english_to_german:
4. Retrieve the German translation.
5. Look up the corresponding French translation in german_to_french.
6. Print the English word, its German translation, and its French translation.
7. End.

PROGRAM:

# Dictionary with English words and their corresponding words in German


english_to_german = {
"hello": "hallo",
"goodbye": "auf Wiedersehen",
"thank you": "danke",
"yes": "ja",
"no": "nein"
}

# Dictionary with German words and their corresponding words in French


german_to_french = {
"hallo": "bonjour",
"auf Wiedersehen": "au revoir",
"danke": "merci",
"ja": "oui",
"nein": "non"
}
# Display the meanings of English words in both German and French
for english_word, german_word in english_to_german.items():
french_word = german_to_french.get(german_word, "Translation not available")
print(f"{english_word}: German - {german_word}, French - {french_word}")

OUTPUT:

GOOGLE COLAB REFERENCE LINK:

Python.ipynb

RESULT:
Thus, python program is successfully implemented that has a set of words in English
language and their corresponding words in German using dictionaries.
Ex no 8 Programs on Numpy Operations
Perform the following operations using numpy.

8.1 Write a program to test whether any of the elements of a given array is non-zero.

AIM:
To write a program to test whether any of the elements of a given array is non-zero.

ALGORITHM:
1. Start a loop to iterate through each element in the array.
2. For each element, check if it is non-zero.
3. If any element is found to be non-zero, break out of the loop.
4. After the loop, check if you broke out early. If so, at least one non-zero element exists.
5. If the loop completes without breaking, all elements are zero.
6. End.

PROGRAM:
import numpy as np
# Original array
array = np.array([0,0,0,0,0,0])
print(array)
# Test whether any of the elements
# of a given array is non-zero
print(np.any(array))

OUTPUT:
GOOGLE COLAB REFERENCE LINK:

Python.ipynb

RESULT:
Thus, python program is successfully implemented to test whether any of the elements of
a given array is non-zero.
8.2 : Write a program to test element-wise for NaN of a given array.

AIM:
To write a program that tests an element-wise for NaN of a given array.

ALGORITHM:
1. Input Array: Begin with the array containing numerical values, including potential NaN
values.
2. Iterate through Elements: Iterate through each element of the array.
3. Check for NaN: For each element, use a conditional statement (e.g., numpy.isnan()
function) to check if it is NaN.
4. Record Results: Keep track of the results, either by storing them in a separate array or
using a boolean mask.
5. Final Output: The final output is a representation of which elements in the array are NaN
and which are not.
6. End.

PROGRAM:
import numpy as np
a=np.array([1,0,np.nan,np.inf])
print("Original array")
print(a)
print("Test element-wise for NaN:")
print(np.isnan(a))

OUTPUT:
GOOGLE COLAB REFERENCE LINK:

Python.ipynb

RESULT:
Thus, python program is successfully implemented to test element-wise for NaN of a
given array.
8.3 Write a program to create an element-wise comparison (greater, greater_equal, less
and less_equal) of two given arrays.

AIM:
To write a program to create an element-wise comparison (greater, greater_equal, less and
less_equal) of two given arrays.

ALGORITHM:
1. Input Arrays: Obtain two arrays to be compared element-wise.
2. Element-wise Comparison: For each pair of corresponding elements in the arrays:
3. Greater (>): Check if the element in the first array is greater than the corresponding
element in the second array.
4. Greater Equal (>=): Check if the element in the first array is greater than or equal to the
corresponding element in the second array.
5. Less (<): Check if the element in the first array is less than the corresponding element in
the second array.
6. Less Equal (<=): Check if the element in the first array is less than or equal to the
corresponding element in the second array.
7. Result: Store or display the results of the element-wise comparisons.

PROGRAM:

import numpy as np
x = np.array([3,5])
y = np.array([2,5])
print("Original numbers :")
print(x)
print(y)
print("Comparison-greater")
print(np.greater(x,y))
print("Comparison - greater_equal")
print(np.greater_equal(x,y))
print("Comparison-less")
print(np.less(x, y))
print("Comparison - less_equal")
print(np.less_equal(x,y))
OUTPUT:

GOOGLE COLAB REFERENCE LINK:

Python.ipynb

RESULT:
Thus, python program is successfully implemented to to create an element-wise
comparison (greater, greater_equal, less and less_equal) of two given arrays.
8.4 : Write a program to create a vector with values ranging from 50 to 90 and print all
values except the first and last.

AIM:
To write a program to create a vector with values ranging from 50 to 90 and print all
values except the first and last.

ALGORITHM:
1. Initialize an empty list.
2. Use a loop to generate values from 50 to 90 and append them to the list.
3. Iterate over the list, excluding the first and last elements.
4. Print each value within the specified range.
5. End.

PROGRAM:
import numpy as np
v = np.arange(50,90)
print("Original vector:")
print(v)
print("All values except the first and last of the said vector:")
print(v[1:-1])

OUTPUT:
GOOGLE COLAB REFERENCE LINK:

Python.ipynb

RESULT:
Thus, python program is successfully implemented to create a vector with values ranging
from 50 to 90 and print all values except the first and last.
8.5 Write a program to sort a given array of shape 2 along the first axis, last axis and on
flattened array.

AIM:
To write a program to sort a given array of shape 2 along the first axis, last axis and on
flattened array.

ALGORITHM:
1. Start the program.
2. Sort along the first axis: Use the numpy.sort function with axis=0 to sort the rows
independently, maintaining column-wise order.
3. Sort along the last axis: Use the numpy.sort function without specifying the axis
parameter, which sorts along the last axis by default. This sorts each column
independently.
4. Sort on flattened array: Use the numpy.flatten or numpy.ravel method to obtain a 1D
array, and then apply numpy.sort to sort the flattened array.
5. End.

PROGRAM:

import numpy as np
a = np.array([[10,40],[30,20]])
print("Original array:" )
print(a)
print("Sort the array along the first axis:" )
print(np.sort(a,axis=0))
print("Sort the array along the last axis:" )
print(np.sort(a))
print("Sort the flattened array:" )
print(np.sort(a,axis=None))
OUTPUT:

GOOGLE COLAB REFERENCE LINK:

Python.ipynb

RESULT:
Thus, python program is successfully implemented to sort a given array of shape 2 along
the first axis, last axis and on flattened array.
8.6 : Write a program to get the indices of the sorted elements of a given array.

AIM:
To write a program to get the indices of the sorted elements of a given array.

ALGORITHM:
1. Create a list of tuples where each tuple contains the original element and its index.
2. Sort the list of tuples based on the elements.
3. Extract the indices from the sorted list, as they represent the order of the elements in the
original array.
4. The resulting list of indices reflects the order of the sorted elements in the original array.
5. End.

PROGRAM:
import numpy as np
student_id = np.array([1023,5202,6230,1671,1682,5241,4532])
print("Original array:")
print(student_id)
i = np.argsort(student_id)
print("Indices of the sorted elements of a given array:")
print(i)

OUTPUT:
GOOGLE COLAB REFERENCE LINK:

Python.ipynb

RESULT:
Thus, python program is successfully implemented to get the indices of the sorted
elements of a given array.
8.7 : Write a program to get the minimum and maximum value of a given array along the
second axis.

AIM:
To write a program to get the minimum and maximum value of a given array along the
second axis.

ALGORITHM:
1. Iterate through the rows of the array along the second axis.
2. Initialize variables to store the minimum and maximum values.
3. For each row, find the minimum and maximum values.
4. Update the variables if a new minimum or maximum is found.
5. After iterating through all rows, the variables hold the minimum and maximum values
along the second axis.
6. End.

PROGRAM:
import numpy as np
x = np.arange(4).reshape((2, 2))
print("Original array:" )
print(x)
print("Maximum value along the second axis:" )
print(np.amax(x, 1))
print("Minimum value along the second axis: ")
print(np.amin(x,1))

OUTPUT:
GOOGLE COLAB REFERENCE LINK:

Python.ipynb

RESULT:
Thus, python program is successfully implemented to get the minimum and maximum
value of a given array along the second axis.
8.8 : Write a program to calculate the difference between the maximum and the minimum
values of a given array along the second axis.

AIM:
To write a program to calculate the difference between the maximum and the minimum
values of a given array along the second axis.

ALGORITHM:
1. Iterate through each row of the array along the second axis.
2. For each row, find the maximum and minimum values.
3. Calculate the difference between the maximum and minimum for each row.
4. Keep track of these differences.
5. After iterating through all rows, determine the maximum difference among them.
6. The result is the maximum difference between the maximum and minimum values along
the second axis of the array.
7. End.

PROGRAM:
import numpy as np
x = np.arange(12).reshape((2, 6))
print("Original array:")
print(x)
rl = np.ptp(x, 1)
r2 = np.amax(x,1)-np.amin(x,1)
assert np.allclose(rl, r2)
print("\n Difference between the maximum and the minimum values of the said array:" )
print(rl)

OUTPUT:
GOOGLE COLAB REFERENCE LINK:

Python.ipynb

RESULT:
Thus, python program is successfully implemented to calculate the difference between
the maximum and the minimum values of a given array along the second axis.
8.9 Write a program to compute the mean, standard deviation, and variance of a given
array along the second axis.

AIM:
To write a program to compute the mean, standard deviation, and variance of a given
array along the second axis.

ALGORITHM:
1. Input: Receive a 2D array.
2. Mean Calculation: Calculate the mean along the second axis using the mean function
along with the axis parameter.
3. Variance Calculation: Compute the variance by squaring the differences between each
element and the mean, then calculate the mean of these squared differences.
4. Standard Deviation: Take the square root of the variance to obtain the standard deviation.
5. Output: Return or display the mean, variance, and standard deviation.
6. End.

PROGRAM:

import numpy as np
x = np.arange(6)
print("\nOriginal array:" )
print(x)

r1 = np.mean(x)
r2 = np.average(x)
assert np.allclose(r1, r2)
print("\nMean: ",r1)

r1 = np.std(x)
r2 = np.sqrt(np.mean((x - np.mean(x))**2))
assert np.allclose(r1 ,r2)
print("\nstd: ",1)

r1= np.var(x)
r2 = np.mean((x-np.mean(x))**2)
assert np.allclose(r1, r2)
print("\nvariance: ",r1)
OUTPUT:

GOOGLE COLAB REFERENCE LINK:

Python.ipynb

RESULT:
Thus, python program is successfully implemented to compute the mean, standard
deviation, and variance of a given array along the second axis.
8.10 Write a program to compute the covariance matrix of two given arrays

AIM:
To write a program to compute the covariance matrix of two given arrays.

ALGORITHM:
1. Import the necessary library, such as NumPy: import numpy as np.
2. Input or define two arrays, say array1 and array2.
3. Use the numpy.cov function, passing both arrays as arguments: cov_matrix =
np.cov(array1, array2).
4. The resulting cov_matrix is the covariance matrix.
5. End.

PROGRAM:
import numpy as np
x = np.array([0, 1, 2])
y = np.array([2, 1, 0])
print("\nOriginal array1: ")
print(x)
print("\nOriginal array1: ")
print(y)
print("\nCovariance matrix of the said arrays: \n" ,np.cov(x,y))

OUTPUT:
GOOGLE COLAB REFERENCE LINK:

Python.ipynb

RESULT:
Thus, python program is successfully implemented to compute the covariance matrix of
two given arrays.
8.11 Write a program to compute the determinant of a given square array.

AIM:
To write a program to compute the determinant of a given square array.

ALGORITHM:
1) Base Case: If the array is 1x1, return the single element as the determinant.
2) Recursive Case (Expansion by Cofactors):
a) Choose any row or column.
b) For each element in that row or column, compute its cofactor by excluding the
current row and column.
c) Multiply each element by its cofactor and add or subtract based on its position.
d) Sum up the results to get the determinant.
3) Recursion Termination: Continue this process until you reach a 2x2 matrix, where you
can compute the determinant directly.
4) End

PROGRAM:
# Importing libraries
import numpy as np
from numpy import linalg

# Creating a 2X2 matrix


matrix = np.array([[1,0],[3,6]])
print("Original 2-D matrix")
print(matrix)

OUTPUT:
GOOGLE COLAB REFERENCE LINK:

Python.ipynb

RESULT:
Thus, python program is successfully implemented to compute the determinant of a given
square array.
8.12 Write a program to compute the sum of the diagonal element of a given array.

AIM:
To write a program to compute the sum of the diagonal element of a given array.

ALGORITHM:
1. Initialize a variable sum_diagonal to zero.
2. Iterate through the rows and columns of the array using nested loops.
3. At each iteration, check if the current row index is equal to the column index.
4. If they are equal, add the element at that position to sum_diagonal.
5. After completing the iteration, sum_diagonal will contain the sum of diagonal elements.
6. Print or return the value of sum_diagonal.
7. End.

PROGRAM:

# importing Numpy package


import numpy as np

# creating a 3X3 Numpy matrix


n_array = np.array([[55, 25, 15],[30, 44, 2],[11, 45, 77]])

# Displaying the Matrix


print("Numpy Matrix is: " )
print(n_array)

# calculating the Trace of a matrix


trace = np.trace(n_array)
print("\nTrace of given 3X3 matrix:" )
print(trace)
OUTPUT:

GOOGLE COLAB REFERENCE LINK:

Python.ipynb

RESULT:
Thus, python program is successfully implemented to compute the sum of the diagonal
element of a given array.
Ex.No:9 - Programs on Pandas
Program on python pandas

9.1 Write a program that performs data wrangling operations for real data set
(Merging,combining,reshaping, pivoting and transformation)

AIM:
To write a program that performs data wrangling operations for real data set
(Merging,combining,reshaping, pivoting and transformation).

ALGORITHM:

1. Import Libraries: Start by importing necessary Python libraries like Pandas and NumPy
for data manipulation.
2. Load Data: Use Pandas to read real datasets into data frames.
3. Merging Data: Combine multiple datasets using common columns with functions like
merge to create a unified dataset.
4. Combining Data: Concatenate or append datasets vertically or horizontally to handle
additional records or variables.
5. Reshaping Data: Reshape data frames using functions like melt to convert wide to long
format or pivot to transform long to wide format.
6. Pivoting Data: Pivot tables to aggregate and summarize data based on specific criteria.
7. Transformation: Apply various data transformations, such as cleaning missing values,
handling outliers, or creating new variables.
8. Exporting Data: Save the processed data using Pandas functions like to_csv or to_excel.
9. End.

PROGRAM:

import pandas as pd

# Create a simple dataset


data1 = {'ID': [1, 2, 3], 'Name': ['Alice', 'Bob', 'Charlie']}
data2 = {'ID': [2, 3, 4], 'Age': [25, 30, 22]}

df1 = pd.DataFrame(data1)
df2 = pd.DataFrame(data2)
# Data Merging: Merge two dataframes based on a common column ('ID')
merged_data = pd.merge(df1, df2, on='ID', how='outer')

# Data Combining: Concatenate two dataframes vertically


combined_data = pd.concat([df1, df2], axis=0)

# Data Reshaping: Pivot the dataframe


pivoted_data = pd.pivot_table(merged_data, values='Age', index='ID', aggfunc='mean')

# Data Transformation: Apply a function to a column


transformed_data = combined_data['ID'].apply(lambda x: x * 2)

# Data Reshaping: Reshape the dataframe using melt


reshaped_data = pd.melt(combined_data, id_vars=['ID'], var_name='Attribute',
value_name='Value')

# Display the results


print("Merged Data:")
print(merged_data)

print("\nCombined Data:")
print(combined_data)

print("\nPivoted Data:")
print(pivoted_data)

print("\nTransformed Data:")
print(transformed_data)

print("\nReshaped Data:")
print(reshaped_data)
PROGRAM:
OUTPUT:

GOOGLE COLAB REFERENCE LINK:

Python.ipynb
RESULT:
Thus, python program is successfully implemented that performs data wrangling
operations for real data set (Merging,combining,reshaping, pivoting and transformation).
9.2 Write a program to perform data aggregation and groupwise operations.

AIM:
To write a program to perform data aggregation and groupwise operations.

ALGORITHM:
1. Data Input: Collect the dataset containing relevant information.
2. Grouping: Identify the key(s) based on which you want to group the data.
3. Groupwise Operations: For each group, apply the desired operations (e.g., sum, average,
count).
4. Aggregation: Aggregate the results of groupwise operations into a summary.
5. Output: Display or store the aggregated data.
6. End.

PROGRAM:
import pandas as pd

# Create a simple dataset


data = {
'Category': ['A', 'B', 'A', 'B', 'A', 'B'],
'Value': [10, 20, 30, 40, 50, 60]
}

df = pd.DataFrame(data)

# Data Aggregation: Group by 'Category' and calculate the sum


aggregated_data = df.groupby('Category').agg({'Value': 'sum'})

# Data Groupwise Operation: Calculate mean and standard deviation for each category
groupwise_stats = df.groupby('Category').agg({'Value': ['mean', 'std']})

# Display the results


print("Original Data:")
print(df)

print("\nAggregated Data (Sum):")


print(aggregated_data)

print("\nGroupwise Operation (Mean and Standard Deviation):")


print(groupwise_stats)
OUTPUT:

GOOGLE COLAB REFERENCE LINK:

Python.ipynb

RESULT:
Thus, python program is successfully implemented to perform data aggregation and
groupwise operations.
9.3 Write a program to perform time series operations on a dataset.

AIM:
To write a program to perform time series operations on a dataset.

ALGORITHM:
1. Data Collection: Gather time-stamped data points over a period.
2. Data Exploration: Understand patterns, trends, and potential anomalies.
3. Time Indexing: Set the time column as the index for chronological ordering.
4. Resampling: Adjust the frequency of data points if needed (e.g., daily to monthly).
5. Feature Engineering: Extract relevant features like lag values or moving averages.
6. Handling Missing Values: Address gaps in the time series data.
7. Differencing: Compute differences between consecutive observations to stabilize trends.
8. Decomposition: Break down the time series into trend, seasonality, and residual
components.
9. Modeling: Apply forecasting models like ARIMA, SARIMA, or machine learning
models.
10. Evaluation: Assess model performance using metrics like Mean Absolute Error (MAE) or
Root Mean Squared Error (RMSE).
11. Visualization: Plot time series, forecasts, and model diagnostics for interpretation.
12. Iterative Refinement: Adjust parameters and models based on evaluation results.

PROGRAM:
import pandas as pd

# Sample data
data = {
'Category': ['A', 'B', 'A', 'B', 'A', 'B'],
'Value': [10, 20, 30, 40, 50, 60]
}

# Create a DataFrame
df = pd.DataFrame(data)

# Group by 'Category' and perform aggregation (e.g., sum)


grouped_data = df.groupby('Category').agg({'Value': 'sum'})

# Display the result


print(grouped_data)
OUTPUT:

GOOGLE COLAB REFERENCE LINK:

Python.ipynb

RESULT:
Thus, python program is successfully implemented to perform time series operations on a
dataset.
` Ex. No:10 - Program on Data Visualization

10.1 Write a program that perform data visualization using Bar chart,Pie chart,Scatter
plot,histogram

AIM:
To write a program that performs data visualization using Bar chart,Pie chart,Scatter
plot,histogram

ALGORITHM:
1. Import Libraries: Import Pandas, Matplotlib, and Seaborn for data manipulation and
visualization.
2. Generate Data: Create a hypothetical dataset with categories and numerical values.
3. Bar Chart: Use Seaborn's barplot to visualize values across categories.
4. Pie Chart: Utilize Matplotlib's pie to represent the distribution of a subset of values as
percentages.
5. Scatter Plot: Create a scatter plot using Matplotlib to show the relationship between two
numerical variables.
6. Histogram: Plot a histogram with Matplotlib to display the frequency distribution of a
single variable.
7. Adjustments: Customize titles, labels, and styling for each plot.
8. Display Plots: Use plt.show() to display the individual plots.
9. Install Dependencies: Ensure Matplotlib and Seaborn are installed (pip install matplotlib
seaborn).
10. Run Program: Execute the script, visualizing the data with bar charts, pie charts, scatter
plots, and histograms.

PROGRAM:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

# Generate a hypothetical dataset


data = {
'Category': ['A', 'B', 'C', 'D', 'E'],
'Value1': [25, 40, 30, 35, 20],
'Value2': [15, 20, 25, 10, 30]
}
df = pd.DataFrame(data)

# Bar chart
plt.figure(figsize=(8, 6))
sns.barplot(x='Category', y='Value1', data=df)
plt.title('Bar Chart')
plt.show()

# Pie chart
plt.figure(figsize=(8, 8))
plt.pie(df['Value2'], labels=df['Category'], autopct='%1.1f%%', startangle=90)
plt.title('Pie Chart')
plt.show()

# Scatter plot
plt.figure(figsize=(8, 6))
plt.scatter(df['Value1'], df['Value2'], c='blue', marker='o')
plt.title('Scatter Plot')
plt.xlabel('Value1')
plt.ylabel('Value2')
plt.show()

# Histogram
plt.figure(figsize=(8, 6))
plt.hist(df['Value1'], bins=np.arange(15, 45, 5), edgecolor='black')
plt.title('Histogram')
plt.xlabel('Value1')
plt.ylabel('Frequency')
plt.show()
OUTPUT:
GOOGLE COLAB REFERENCE LINK:

Python.ipynb

RESULT:
Thus, python program is successfully implemented that performs data visualization using
Bar chart,Pie chart,Scatter plot,histogram

You might also like