Python Lab 1

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 16

#1.

Develop a python program to read n digit integer number,


and separate the integer number and display each digit. use
floor and mod operators.
'''Algorithm...
Start:

Define the function display_digits that takes an integer number as input.


Input:

Get a positive integer number from the user.


Function Definition:

Define the function display_digits:


Check if the input number is a positive integer.
If not, print an error message and return.
Initialize an empty list digits to store the separated digits.
Separate Digits:

Use a while loop to iterate as long as the number is greater than 0:


Inside the loop:
Use the modulus operator (%) to extract the last digit.
Insert the digit at the beginning of the digits list.
Use the floor division operator (//) to remove the last digit.
Display Digits:

Print a message indicating that the following are the digits of the number.
Use a for loop to iterate through the digits list and print each digit.
End:

End the program.


'''

#Program

def display_digits(number):
# Ensure the input is a positive integer
if not isinstance(number, int) or number < 0:
print("Please enter a positive integer.")
return

# Process each digit using floor and mod operators


digits = []
while number > 0:
digit = number % 10 # Extract the last digit
digits.insert(0, digit) # Insert the digit at the beginning of the list
number = number // 10 # Remove the last digit using floor division

# Display each digit


print("Digits of the number:")
for digit in digits:
print(digit)

# Get input from the user


try:
n = int(input("Enter a positive integer: "))
display_digits(n)
except ValueError:
print("Invalid input. Please enter a valid integer.")

Output:
Enter a positive integer: 5678
Digits of the number:
5
6
7
8

#2. Develop a python program to accept 4 numbers and display


them in sorted order using a minimum number of if else
statements.
'''Algorithm...
Start:

Get input from the user for four numbers (num1, num2, num3, num4).
Input Validation:

Use a try block and float() function to convert user input to floating-point numbers.
If the input is invalid, print an error message and exit the program.
Bubble Sort:

Use a series of if-else statements to perform the bubble sort:


Compare and swap num1 and num2 if num1 is greater than num2.
Compare and swap num2 and num3 if num2 is greater than num3.
Compare and swap num3 and num4 if num3 is greater than num4.
Repeat the above steps to ensure that the largest number is at the end.
Continue the process for the remaining elements.
Display Sorted Numbers:

Print the sorted numbers (num1, num2, num3, num4).


End:

End the program.


'''

# Get input from the user


try:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))
num4 = float(input("Enter the fourth number: "))
except ValueError:
print("Invalid input. Please enter valid numbers.")
exit()

# Bubble sort algorithm


if num1 > num2:
num1, num2 = num2, num1

if num2 > num3:


num2, num3 = num3, num2

if num3 > num4:


num3, num4 = num4, num3

if num1 > num2:


num1, num2 = num2, num1

if num2 > num3:


num2, num3 = num3, num2

if num1 > num2:


num1, num2 = num2, num1

# Display the sorted numbers


print("Numbers in sorted order:", num1, num2, num3, num4)

Output:
Enter the first number: 5
Enter the second number: 2
Enter the third number: 4
Enter the fourth number: 7
Numbers in sorted order: 2.0 4.0 5.0 7.0

3. Develop python script to calculate the mean, median, mode,


variance and standard deviation of n integers numbers.
'''Algorithm...
Start:

Define the function calculate_mean that takes a list of numbers as input and returns the mean.
Define the function calculate_median that takes a list of numbers as input and returns the median.
Define the function calculate_mode that takes a list of numbers as input and returns the mode(s).
Define the function calculate_variance that takes a list of numbers and the mean as input, and returns
the variance.
Define the function calculate_standard_deviation that takes the variance as input and returns the
standard deviation.
Input:

Get input from the user for the number of integers (n).
Input Numbers:

Get input from the user for a list of n integers.


Calculate Mean:

Call the calculate_mean function with the list of numbers.


Store the result in the variable mean.
Calculate Median:

Call the calculate_median function with the list of numbers.


Store the result in the variable median.
Calculate Mode:

Call the calculate_mode function with the list of numbers.


Store the result in the variable mode.
Calculate Variance:

Call the calculate_variance function with the list of numbers and the calculated mean.
Store the result in the variable variance.
Calculate Standard Deviation:

Call the calculate_standard_deviation function with the calculated variance.


Store the result in the variable std_dev.
Display Results:

Print the calculated mean, median, mode, variance, and standard deviation.
End:

End the program.


'''

def calculate_mean(numbers):
return sum(numbers) / len(numbers)

def calculate_median(numbers):
sorted_numbers = sorted(numbers)
n = len(sorted_numbers)
mid = n // 2
if n % 2 == 0:
return (sorted_numbers[mid - 1] + sorted_numbers[mid]) / 2
else:
return sorted_numbers[mid]

def calculate_mode(numbers):
# Calculate the frequency of each number
frequency_dict = {}
for num in numbers:
if num in frequency_dict:
frequency_dict[num] += 1
else:
frequency_dict[num] = 1

# Find the mode(s)


max_frequency = max(frequency_dict.values())
mode = [num for num, freq in frequency_dict.items() if freq == max_frequency]

return mode

def calculate_variance(numbers, mean):


squared_diff = [(x - mean) ** 2 for x in numbers]
return sum(squared_diff) / len(numbers)

def calculate_standard_deviation(variance):
return variance ** 0.5

# Get input from the user for n


try:
n = int(input("Enter the number of integers (n): "))
except ValueError:
print("Invalid input. Please enter a valid integer.")
exit()

# Get input from the user for the list of integers


try:
numbers = [int(input(f"Enter integer #{i + 1}: ")) for i in range(n)]
except ValueError:
print("Invalid input. Please enter valid integers.")
exit()
# Calculate and display the mean
mean = calculate_mean(numbers)
print(f"Mean: {mean}")

# Calculate and display the median


median = calculate_median(numbers)
print(f"Median: {median}")

# Calculate and display the mode


mode = calculate_mode(numbers)
print(f"Mode: {mode}")

# Calculate and display the variance


variance = calculate_variance(numbers, mean)
print(f"Variance: {variance}")

# Calculate and display the standard deviation


std_dev = calculate_standard_deviation(variance)
print(f"Standard Deviation: {std_dev}")

Output:

Enter the number of integers (n): 3


Enter integer #1: 4
Enter integer #2: 5
Enter integer #3: 3
Mean: 4.0
Median: 4
Mode: [4, 5, 3]
Variance: 0.6666666666666666
Standard Deviation: 0.816496580927726

#4. Develop a python program for checking if a given n digit


number is palindrome or not. use // and % operator with loop
stateme.
'''Algorithm...
Start:

Define the function is_palindrome that takes an integer number as input.


Input:

Get input from the user for the number of digits (n).
Validate that n is a positive integer.
Input Number:

Get input from the user for an n-digit number.


Validate that the input is a non-negative integer.
Function Definition:

Define the function is_palindrome:


Initialize variables original_number and reversed_number with the input number.
Use a while loop to iterate as long as number is greater than 0:
Inside the loop:
Use the modulus operator (%) to extract the last digit.
Multiply reversed_number by 10 and add the extracted digit.
Use the floor division operator (//) to remove the last digit.
Check if original_number is equal to reversed_number.
Return True if they are equal; otherwise, return False.
Check Palindrome:

Call the is_palindrome function with the input number.


If the result is True, print that the number is a palindrome.
If the result is False, print that the number is not a palindrome.
End:

End the program.


'''

def is_palindrome(number):
original_number = number
reversed_number = 0

while number > 0:


digit = number % 10
reversed_number = reversed_number * 10 + digit
number = number // 10

return original_number == reversed_number

# Get input from the user for the n-digit number


try:
n = int(input("Enter the number of digits (n): "))
if n <= 0:
print("Please enter a positive integer for the number of digits.")
exit()
except ValueError:
print("Invalid input. Please enter a valid integer.")
exit()

try:
num = int(input(f"Enter a {n}-digit number: "))
except ValueError:
print("Invalid input. Please enter a valid integer.")
exit()

if num < 0:
print("Please enter a non-negative integer.")
exit()

# Check if the number is a palindrome


if is_palindrome(num):
print(f"{num} is a palindrome.")
else:
print(f"{num} is not a palindrome.")

Output:
Enter the number of digits (n): 3
Enter a 3-digit number: 121
121 is a palindrome.
#5. Develop a python script to display a multiplicaion table for
given integer n.
'''Algorithm...
Start:

Get input from the user for the integer n.


Input Validation:

Validate that the input is a valid integer. If not, print an error message and exit.
Display Multiplication Table:

Print a header indicating that the following is the multiplication table for n.
Loop Through Multiplication Table:

Use a for loop to iterate from 1 to 10 (inclusive).


Inside the loop:
Calculate the result of the multiplication (n * i).
Print the multiplication expression and result in the format "n x i = result".
End:

End the program.


'''

# Get input from the user for the integer n


try:
n = int(input("Enter an integer to display its multiplication table: "))
except ValueError:
print("Invalid input. Please enter a valid integer.")
exit()

# Display the multiplication table for n


print(f"Multiplication Table for {n}:")

for i in range(1, 11):


result = n * i
print(f"{n} x {i} = {result}")

Output:
Enter an integer to display its multiplication table: 2
Multiplication Table for 2:
2x1=2
2x2=4
2x3=6
2x4=8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20
#6. Develop a python script to rotate right about a given position
in that list and display them

'''Algorithm…

Start:

Define a function rotate_right that takes a list and a position as input and returns the list rotated to
the right about that position.
Input:

Prompt the user to enter a list of integers, separated by space.


If the input contains non-integer values, print an error message and exit.
Prompt the user to enter an integer for the rotation position.
If the input is not a valid integer, print an error message and exit.
Rotate List:

Call the rotate_right function with the user-input list and rotation position.
Store the result in a variable.
Display Result:

Print the original list entered by the user.


Print the rotated list based on the specified rotation position.
End:

End the program.


'''

Code

def rotate_right(lst, position):


# Ensure the position is within the valid range
position = position % len(lst)

# Rotate the list to the right


rotated_list = lst[-position:] + lst[:-position]

return rotated_list

# Get input from the user for the list of numbers


try:
elements = input("Enter elements of the list separated by space: ").split()
original_list = [int(element) for element in elements]
except ValueError:
print("Invalid input. Please enter valid integers.")
exit()

# Get input from the user for the rotation position


try:
rotation_position = int(input("Enter the rotation position: "))
except ValueError:
print("Invalid input. Please enter a valid integer for the rotation position.")
exit()

# Rotate the list to the right about the given position


result_list = rotate_right(original_list, rotation_position)

# Display the original and rotated lists


print("Original List:", original_list)
print(f"Rotated Right by {rotation_position} positions:", result_list)

Output

Enter elements of the list separated by space: 1 4 5 -10


Enter the rotation position: 2
Original List: [1, 4, 5, -10]
Rotated Right by 2 positions: [5, -10, 1, 4]

#7. Develop a python script to interchange the digits of a given integer number.

'''Algorithm...
Start:

Define a function interchange_digits that takes an integer, digit1, and digit2 as input and returns the
number with the specified digits interchanged.
Input:

Prompt the user to enter an integer number.


If the input is not a valid integer, print an error message and exit.
Prompt the user to enter the first digit to interchange.
If the input is not a valid digit, print an error message and exit.
Prompt the user to enter the second digit to interchange.
If the input is not a valid digit, print an error message and exit.
Interchange Digits:

Call the interchange_digits function with the user-input number, digit1, and digit2.
Store the result in a variable.
Display Result:

Print the original number entered by the user.


Print the interchanged number based on the specified digits.
End:

End the program.


'''
Code

def interchange_digits(number, digit1, digit2):


# Convert the number to a list of digits
digits_list = [int(digit) for digit in str(number)]

# Find the positions of the digits to interchange


position1 = digits_list.index(digit1)
position2 = digits_list.index(digit2)

# Interchange the digits


digits_list[position1], digits_list[position2] = digits_list[position2], digits_list[position1]

# Convert the list of digits back to an integer


result_number = int(''.join(map(str, digits_list)))

return result_number

# Get input from the user for the integer number


try:
input_number = int(input("Enter an integer number: "))
except ValueError:
print("Invalid input. Please enter a valid integer.")
exit()

# Get input from the user for the digits to interchange


try:
digit1 = int(input("Enter the first digit to interchange: "))
digit2 = int(input("Enter the second digit to interchange: "))
except ValueError:
print("Invalid input. Please enter valid digits.")
exit()

# Interchange the digits of the given number


result = interchange_digits(input_number, digit1, digit2)

# Display the original and interchanged numbers


print(f"Original Number: {input_number}")
print(f"Interchanged Number: {result}")

Output

Enter an integer number: 23456


Enter the first digit to interchange: 3
Enter the second digit to interchange: 5
Original Number: 23456
Interchanged Number: 25436

#8. Develop a python program to capitalize a given list of strings.


'''Algorithm...
Start:

Define the function capitalize_strings that takes a list of strings as input.


Input:

Get input from the user for a list of strings.


Function Definition:

Define the function capitalize_strings:


Use list comprehension to iterate through each string in the input list and capitalize it.
Return the list of capitalized strings.
Capitalization:

Call the capitalize_strings function with the input list of strings.


Store the result in a variable.
Display Result:

Print the original list of strings.


Print the list of capitalized strings.
End:

End the program.


'''

Code:

def capitalize_strings(string_list):
# Use list comprehension to capitalize each string
capitalized_list = [word.capitalize() for word in string_list]
return capitalized_list

# Get input from the user for the list of strings


try:
input_strings = input("Enter a list of strings separated by space: ").split()
except ValueError:
print("Invalid input. Please enter valid strings.")
exit()

# Capitalize the strings in the given list


result = capitalize_strings(input_strings)

# Display the original and capitalized lists


print("Original List:", input_strings)
print("Capitalized List:", result)

Output
Enter a list of strings separated by space: hello good
Original List: ['hello', 'good']
Capitalized List: ['Hello', 'Good']

#9. Using a dictionary, develop a python program to determine


and print the number of duplicate words in a sentence.
'''Algorithm...
Start:

Define the function count_duplicate_words that takes a sentence as input.


Input:

Get input from the user for the sentence.


Function Definition:

Define the function count_duplicate_words:


Split the sentence into words.
Create an empty dictionary word_freq to store word frequencies.
Iterate through each word in the sentence:
Convert the word to lowercase to treat words case-insensitively.
If the word is already in word_freq, increment its frequency; otherwise, add it to the dictionary with a
frequency of 1.
Filter out words with frequency greater than 1 (duplicates) into a new dictionary duplicates.
Return the duplicates dictionary.
Count Duplicates:

Call the count_duplicate_words function with the input sentence.


Store the result in a variable.
Display Result:

If no duplicate words are found, print a message indicating that.


If duplicate words are found, print the duplicate words and their frequencies.
End:

End the program.


'''
Code
def count_duplicate_words(sentence):
# Split the sentence into words
words = sentence.split()

# Create a dictionary to store word frequencies


word_freq = {}

# Count the frequency of each word


for word in words:
word = word.lower() # Convert to lowercase to treat words case-insensitively
if word in word_freq:
word_freq[word] += 1
else:
word_freq[word] = 1

# Filter words with frequency greater than 1 (duplicates)


duplicates = {word: freq for word, freq in word_freq.items() if freq > 1}

return duplicates

# Get input from the user for the sentence


sentence = input("Enter a sentence: ")

# Determine and print the number of duplicate words


duplicates = count_duplicate_words(sentence)
if not duplicates:
print("No duplicate words found.")
else:
print("Duplicate words and their frequencies:")
for word, freq in duplicates.items():
print(f"{word}: {freq}")

Output
Enter a sentence: A woman is in love with a woman
Duplicate words and their frequencies:
a: 2
woman: 2

#10. Develop a python program to read Numpy array and print


row (sum, mean, std) and column (sum, mean, std).
'''Algorithm...
Start:

Import the NumPy library (import numpy as np).


Function Definition (print_row_statistics):

Define a function print_row_statistics that takes a 2D NumPy array as input.


Iterate over each row of the array.
For each row, calculate and print the sum, mean, and standard deviation.
Function Definition (print_column_statistics):

Define a function print_column_statistics that takes a 2D NumPy array as input.


Iterate over each column of the array.
For each column, calculate and print the sum, mean, and standard deviation.
Input:

Get input from the user for the number of rows and columns in the array.
Input Array Elements:

Get input from the user for each element of the 2D array.
Create NumPy Array:

Use the input values to create a 2D NumPy array.


Print Row Statistics:

Call the print_row_statistics function with the 2D array as input.


Print the row statistics.
Print Column Statistics:

Call the print_column_statistics function with the 2D array as input.


Print the column statistics.
End:

End the program.


'''

Code

import numpy as np

def print_row_statistics(array):
for i, row in enumerate(array):
row_sum = np.sum(row)
row_mean = np.mean(row)
row_std = np.std(row)
print(f"Row {i + 1} - Sum: {row_sum}, Mean: {row_mean}, Std Dev: {row_std}")

def print_column_statistics(array):
for j in range(array.shape[1]):
col_sum = np.sum(array[:, j])
col_mean = np.mean(array[:, j])
col_std = np.std(array[:, j])
print(f"Column {j + 1} - Sum: {col_sum}, Mean: {col_mean}, Std Dev: {col_std}")

# Get input from the user for the number of rows and columns
try:
rows = int(input("Enter the number of rows: "))
cols = int(input("Enter the number of columns: "))
except ValueError:
print("Invalid input. Please enter valid integers.")
exit()

# Get input from the user for the 2D array


try:
array = np.array([[float(input(f"Enter element at position ({i + 1}, {j + 1}): ")) for j in range(cols)] for i
in range(rows)])
except ValueError:
print("Invalid input. Please enter valid numbers.")
exit()
# Print row statistics
print("Row Statistics:")
print_row_statistics(array)

# Print column statistics


print("\nColumn Statistics:")
print_column_statistics(array)

Output
Enter the number of rows: 2
Enter the number of columns: 3
Enter element at position (1, 1): 2
Enter element at position (1, 2): 3
Enter element at position (1, 3): 4
Enter element at position (2, 1): 1
Enter element at position (2, 2): 2
Enter element at position (2, 3): 3
Row Statistics:
Row 1 - Sum: 9.0, Mean: 3.0, Std Dev: 0.816496580927726
Row 2 - Sum: 6.0, Mean: 2.0, Std Dev: 0.816496580927726

Column Statistics:
Column 1 - Sum: 3.0, Mean: 1.5, Std Dev: 0.5
Column 2 - Sum: 5.0, Mean: 2.5, Std Dev: 0.5
Column 3 - Sum: 7.0, Mean: 3.5, Std Dev: 0.5

#11. Develop a python program to read and print in the console


CSV fie
'''Algorithm...
Start:

Import the csv module.


Function Definition (read_and_print_csv):

Define a function read_and_print_csv that takes the path to a CSV file as input.
Try to open the CSV file for reading.
If the file is not found, print an error message and exit.
If any other error occurs, print the error message and exit.
Create a CSV reader using csv.reader.
Iterate through each row in the CSV file:
Print the current row.
Input:

Get input from the user for the path to the CSV file.
Read and Print CSV:

Call the read_and_print_csv function with the user-input file path.


End:

End the program.


'''

Code
import csv

def read_and_print_csv(file_path):
try:
with open(file_path, 'r') as csvfile:
# Create a CSV reader
csv_reader = csv.reader(csvfile)

# Iterate through each row in the CSV file and print it


for row in csv_reader:
print(row)
except FileNotFoundError:
print(f"File not found: {file_path}")
except Exception as e:
print(f"An error occurred: {e}")

# Get input from the user for the CSV file path
file_path = input("Enter the path to the CSV file: ")

# Read and print the contents of the CSV file


read_and_print_csv(file_path)

Output
Enter the path to the CSV file: 3.csv
['sunny', 'Warm', 'Normal', 'Strong', 'Warm', 'Same', 'Yes']
['Sunny', 'Warm', 'High', 'Strong', 'Warm', 'Same', 'Yes']
['Rainy', 'Cold', 'High', 'Strong', 'Warm', 'Change', 'No']
['Sunny', 'Warm', 'High', 'Strong', 'Warm', 'Change', 'Yes']

#12. Develop a python program to read a HTML file with basic


tags, and construct a dictionary and display the same in the
console
'''Algorithm...
Start:

Import the BeautifulSoup library from bs4.


Function Definition (construct_html_dictionary):

Define a function construct_html_dictionary that takes HTML content as input.


Create an empty dictionary (html_dict) to store extracted information.
Use BeautifulSoup to parse the HTML content.
Extract data from basic tags (title, headings, paragraphs, and links) and add it to the html_dict.
Return the constructed dictionary.
Input:

Get input from the user for the path to the HTML file.
Read HTML File:

Try to open the HTML file for reading.


If the file is not found, print an error message and exit.
If any other error occurs, print the error message and exit.
Read the HTML content from the file.
Construct HTML Dictionary:
Call the construct_html_dictionary function with the HTML content.
Store the result in a variable.
Display HTML Dictionary:

Print the constructed HTML dictionary in the console.


End:

End the program


'''

Code

from bs4 import BeautifulSoup

def construct_html_dictionary(html_content):
html_dict = {}

soup = BeautifulSoup(html_content, 'html.parser')

# Extract data from basic tags


html_dict['title'] = soup.title.text if soup.title else None
html_dict['headings'] = [heading.text for heading in soup.find_all(['h1', 'h2', 'h3', 'h4', 'h5', 'h6'])]
html_dict['paragraphs'] = [paragraph.text for paragraph in soup.find_all('p')]
html_dict['links'] = [link.get('href') for link in soup.find_all('a')]

return html_dict

# Get input from the user for the HTML file path
html_file_path = input("Enter the path to the HTML file: ")

# Read HTML file content


try:
with open(html_file_path, 'r', encoding='utf-8') as html_file:
html_content = html_file.read()
except FileNotFoundError:
print(f"File not found: {html_file_path}")
exit()
except Exception as e:
print(f"An error occurred: {e}")
exit()

# Construct and display the HTML dictionary


html_dict = construct_html_dictionary(html_content)
print("HTML Dictionary:")
print(html_dict)
Output
Enter the path to the HTML file: html.html
HTML Dictionary:
{'title': 'Page Title', 'headings': ['This is a header'], 'paragraphs': ['This is a paragraph.', 'Click Me!'],
'links': ['https://oversixtydev.blob.core.windows.net/media/23311/hero.jpg']}

You might also like