1)
Aim: To write the program to find the largest element among three numbers.
Desccription:
Initialize three numbers by n1, n2, and n3. Add three numbers into the list lst = [n1, n2, n3]. . Using the max() function to find the greatest number max(lst). And finally, we will print the maximum number.
Program:
# Python program to find the largest number among the three input numbers
# change the values of num1, num2 and num3
# for a different result
num1 = 10
num2 = 14
num3 = 12
# uncomment following lines to take three numbers from user
#num1 = float(input("Enter first number: "))
#num2 = float(input("Enter second number: "))
#num3 = float(input("Enter third number: "))
if (num1 >= num2) and (num1 >= num3):
largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3
print("The largest number is", largest)
Output:
The largest number is 14.0
Result:The python program to find the largest element among three numbers was successfully completed.
2)
Aim:The program to display all prime numbers within an interval.
Description:
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. The first few prime numbers are {2, 3, 5, 7, 11, ….}.
The idea to solve this problem is to iterate the val from start to end using a Python loop and for every number, if it is greater than 1, check if it divides n. If we find any other number which divides, print that value.
# Python program to display all the prime numbers within an interval
lower = 900
upper = 1000
print("Prime numbers between", lower, "and", upper, "are:")
for num in range(lower, upper + 1):
# all prime numbers are greater than 1
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)
Output:
Prime numbers between 900 and 1000 are:
907
911
919
929
937
941
947
953
967
971
977
983
Result: The python program to display all prime numbers within an interval was successfully completed.
3)
Aim:To write python program to swap two numbers without using a temorary variable.
Description:
This program is used to swap values of two variables using the third variable, which is the temporary variable. So first of all, you have to include the stdio header file using the "include" preceding by which tells that the header file needs to be process before compilation, hence named preprocessor directive.
x = 10
y = 5
# Code to swap 'x' and 'y'
# x now becomes 15
x = x + y
# y becomes 10
y = x - y
# x becomes 5
x = x - y
print("After Swapping: x =", x, " y =", y)
Output:
After Swapping: x =5, y=10
Result: The python program to swap two numbers without using a temorary variable was successfully completed.
4)Aim:To Demonstrate the following operators in python with suitable examples:
a)Arithmetic b)Relational c)Assignment d)Logical e)Bit wise f)Ternary g)Membership h)Identity.
Description:
#Python Arithmetic operators are used to perform basic mathematical operations like addition, subtraction, multiplication, and division.
#In Python Comparison of Relational operators compares the values. It either returns True or False according to the condition.
#Python Logical operators perform Logical AND, Logical OR, and Logical NOT operations. It is used to combine conditional statements.
#Python Bitwise operators act on bits and perform bit-by-bit operations. These are used to operate on binary numbers.
#Python Assignment operators are used to assign values to the variables.
#In Python, is and is not are the identity operators both are used to check if two values are located on the same part of the memory. Two variables that are equal do not imply that they are identical.
#In Python, in and not in are the membership operators that are used to test whether a value or variable is in a sequence.
#in Python, Ternary operators also known as conditional expressions are operators that evaluate something based on a condition being true or false.
4.a)
a = 7
b = 2
# addition
print ('Sum: ', a + b)
# subtraction
print ('Subtraction: ', a - b)
# multiplication
print ('Multiplication: ', a * b)
# division
print ('Division: ', a / b)
# floor division
print ('Floor Division: ', a // b)
# modulo
print ('Modulo: ', a % b)
# a to the power b
print ('Power: ', a ** b)
Output:
Sum: 9
Subtraction: 5
Multiplication: 14
Division: 3.5
Floor Division: 3
Modulo: 1
Power: 49
4.b)
Initializing the value of a and b
a = 20
b = 10
d = 30
# Calculating the sum of a and b
c = a + b
e = d - b
print("The sum of a and b is ", c)
print("The difference of d and b is ", e)
# Using relational operators
print(a >= b)
print(a != b)
print(c <= d)
print(e == a)
Output:
The sum of a and b is 30
The difference of d and b is 20
True
True
True
True
4.c)
# assign 10 to a
a = 10
# assign 5 to b
b = 5
# assign the sum of a and b to a
a += b # a = a + b
print(a)
Output:
15
4.d)
# logical AND
print(True and True)
print(True and False)
# logical OR
print(True or False)
# logical NOT
print(not True)
Output:
True
False
True
False
4.e)
x = int(input("Enter the value of x: ")) # Taking user input for x
y = int(input("Enter the value of y: ")) # Taking user input for y
print("x & y =", x & y)
print("x | y =", x | y)
print("~y =", ~ y)
print("x ^ y =", x ^ y)
print("x >> 1 =", x >> 3)
print("y >> 1 =", y >> 3)
print("x << 1 =", x << 1)
print("y << 1 =", y << 1)
Output:
Enter the value of x: 4
Enter the value of y: 5
x & y = 4
x | y = 5
~y = -6
x ^ y = 1
x >> 1 = 0
y >> 1 = 0
x << 1 = 8
y << 1 = 10
4.f)
message = 'Hello world'
dict1 = {1:'a', 2:'b'}
# check if 'H' is present in message string
print('H' in message) # prints True
# check if 'hello' is present in message string
print('hello' not in message) # prints True
# check if '1' key is present in dict1
print(1 in dict1) # prints True
# check if 'a' key is present in dict1
print('a' in dict1) # prints False
Output:
True
True
True
False
4.g)
x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
x3 = [1,2,3]
y3 = [1,2,3]
print(x1 is not y1)
print(x2 is y2)
print(x3 is y3)
Output:
False
True
False
4.h)
num1 = 30
num2 = 50
#Use ternary operator
print(num1,"is greater") if (num1 > num2) else print(num2,"is greater")
Output:
50 is greater
Result: The Demonstration of the operators in python with suitable examples was successfully completed.
5)
Aim:To write the python program to add and multiply complex numbers.
Description:
Addition of complex number: In Python, complex numbers can be added using + operator.
Examples:
Input: 2+3i, 4+5i
Output: Addition is : 6+8i
Input: 2+3i, 1+2i
Output: Addition is : 3+5i
When you multiply two complex numbers, for example, a+bj and c+dj, the resulting complex number is (ac-bd)+(ad+bc)j. Note that multiplying the imaginary unit with itself results in the real value -1,
j*j = -1.
Program:
print("Addition of two complex numbers : ",(4+3j)+(3-7j))
print("Subtraction of two complex numbers : ",(4+3j)-(3-7j))
print("Multiplication of two complex numbers : ",(4+3j)*(3-7j))
Output:
Addition of two complex numbers : (7-4j)
Subtraction of two complex numbers : (1+10j)
Multiplication of two complex numbers : (33-19j)
Result:The python program to add and multiply complex numbers was successfully executed.
6)
Aim:To write the python program to print mutiplication table of a given number.
Description:
A multiplication chart is a table that shows the products of two numbers. Usually, one set of numbers is written on the left column and another set is written as the top row. The products are listed as a rectangular array of numbers. Multiplication is repeated addition.
Program:
# Multiplication table (from 1 to 10) in Python
num = 12
# To take input from the user
# num = int(input("Display multiplication table of? "))
# Iterate 10 times from i = 1 to 10
for i in range(1, 11):
print(num, 'x', i, '=', num*i)
Output:
12 x 1 = 12
12 x 2 = 24
12 x 3 = 36
12 x 4 = 48
12 x 5 = 60
12 x 6 = 72
12 x 7 = 84
12 x 8 = 96
12 x 9 = 108
12 x 10 = 120
Result: python program to print mutiplication table of a given number was successfully completed
7)Aim:To write the python program to define a function with multiple return values.
Description:
In Python, you can return multiple values by simply separating them with commas in the return statement. In Python, comma-separated values are treated as tuples, even without parentheses, unless the syntax requires them. Therefore, the function in the example above returns a tuple.
Program:
def name():
return "John","Armin"
# print the tuple with the returned values
print(name())
# get the individual items
name_1, name_2 = name()
print(name_1, name_2)
Output:
('John', 'Armin')
John Armin
Result: The python program to define a function with multiple return values was successfully completed.
8)Aim:To write the python program to define a function using default arguments.
Description:
Default arguments in Python represent the function arguments that will be used if no arguments are passed to the function call. The default arguments are represented as argument_name = value in the function definition. Default arguments in Python can be used with keyword and positional arguments.
Program:
def add_numbers( a = 7, b = 8):
sum = a + b
print('Sum:', sum)
# function call with two arguments
add_numbers(2, 3)
# function call with one argument
add_numbers(a = 2)
# function call with no arguments
add_numbers()
Output:
Sum: 5
Sum: 10
Sum: 15
Result: The python program to define a function using default arguments was successfully executed.
9)Aim:To write the python program to find the length of the string without using any library functions.
Description:
In Python, you can find the length of a string using the len() function. For example: Python code example:- my_string = "Hello, World!" length_of_string = len(my_string) print(length_of_string) This will output the length of the string, which in this case is 13.
Program:
#take user input
string = 'Hello'
count = 0
for i in string:
count+=1
print(count)
Output:
5
Result: The python program to find the length of the string without using any library functions was successfully completed.
10)Aim:The program to check if the substring is present in a given string or not.
Description:
In Python, you can easily check if a substring is present in a given string using the in operator. The in operator is used to test whether a particular value (substring) exists within a sequence.
In Python, you can check python substring in string is present using an if-else statement. The if-else statement allows you to conditionally execute different blocks of code based on whether the condition is true or false.
Program:
text = "Geeks welcome to the Geek Kingdom!"
if "Geek" in text:
print("Substring found!")
else:
print("Substring not found!")
if "For" in text:
print("Substring found!")
else:
print("Substring not found!")
Output:
Substring found!
Substring not found!
Result: The program to check if the substring is present in a given string or not was successfully completed.
11)Aim:The program to perform the given operations on a list:
1)addition 2)insertion3)slicing.
Description:
Addition:
Basic list operations in Python include performing basic arithmetic on the numbers contained within a list, accessing elements of an existing list, replacing elements of a list, rearranging elements of a list, concatenating multiple lists together, and duplicating specific entries in a list.
Insertion:
Now we can insert an element in between the list using the inbuilt function of Python list operation insert()
Slicing:
This method is used to print a section of the list. Which means we can display elements of a specific index.
Python
print("The elements of list in the range of 3 to 12 are:\n",my_list[3:12])
You can also try this code with Online Python Compiler
Run Code
Using the slicing operator, we have sliced elements from range of 3 to 12 in the my_list. Hence the above code would print elements whose index lies between the range 3 to 12.
Program:
Python
my_list.insert(5,30)
print("The list after insert() operator is: \n",my_list)
ADDITION
myList = [1, 2, 3, 'EduCBA']
myList.append(4)
myList.append(5)
myList.append(6)
for i in range(7, 9):
myList.append(i)
print(myList)
Output;
[1,2,3,‘EduCBA’,4,5,6 ]
INSERTION
myList = [1, 2, 3, 'EduCBA' ]
myList.insert(3, 4)
myList.insert(4, 5)
myList.insert(5, 6)
print(myList)
Output:
[1,2,3,4,5,6,‘EduCBA’]
SLICING
myList = [1, 2, 3, 'EduCBA']
print(myList[:4])
print(myList[2:])
print(myList[2:4])
print(myList[:])
Output:
[1,2,3,’EduCBA’]
[3,’EduCBA’]
[3,’EduCBA’]
[1,2,3,’EduCBA’]
Result:The pyhton program to perform addition,insertion and slicing operations was successfully executed.
12)Aim:The program to perform any 5 built-in functions by taking any list.
Description:
Built-in functions are similar to operation codes in that they perform operations on data you specify. Built-in functions can be used in expressions. Additionally, constant-valued built-in functions can be used in named constants. These named constants can be used in any specification.
globals() Returns the current global symbol table as a dictionary
hasattr() Returns True if the specified object has the specified attribute (property/method)
hash() Returns the hash value of a specified object
help() Executes the built-in help system
Programs:
a)integer = -20
print('Absolute value of -40 is:', abs(integer))
Output:
Absolute value of -20 is : 20
b)all values true
k = [1, 3, 4, 6]
print(all(k))
Output:
True
c)x = 10
y = bin(x)
print (y)
Output:
Ob1010
d)string = "Hello World."
array = bytes(string, 'utf-8')
print(array)
Output:
b Hello World
e)x = 8
print(callable(x))
Output:
False
Result: The program to perform any 5 built-in functions by taking any list was successfully executed.
13)Aim:The program to create tuples(name,age,address,college) for at least two members and concatenate the tuples and print the concatenated tuples.
Description:
The tuples are concatenated to create a nested tuple using the , operator and assigned to the variable res. Here, the + operator is used to concatenate two tuples and create a new tuple. Finally, the result is printed using the print() function and string concatenation using the + operator.
Program:
# Python3 code to demonstrate working of
# Ways to concatenate tuples
# using + operator
# initialize tuples
test_tup1 = (1, 3, 5)
test_tup2 = (4, 6)
# printing original tuples
print("The original tuple 1 : " + str(test_tup1))
print("The original tuple 2 : " + str(test_tup2))
# Ways to concatenate tuples
# using + operator
res = test_tup1 + test_tup2
# printing result
print("The tuple after concatenation is : " + str(res))
Output :
The original tuple 1 : (1, 3, 5)
The original tuple 2 : (4, 6)
The tuple after concatenation is : (1, 3, 5, 4, 6)
Result: The program to create tuples(name,age,address,college) for at least two members and concatenate the tuples and print the concatenated tuples was executed.
14)Aim:The program to count the number vowels in a string (no control flow allowed).
Description:
Step 1: Take a string from the user and store it in a variable.
Step 2: Initialize a count variable to 0.
Step 3: Use a for loop to traverse through the characters in the string.
Step 4: Use an if statement to check if the character is a vowel or not and increment the count variable if it is a vowel.
Program:
#take user input
String = input('Enter the string :')
count = 0
#to check for less conditions
#keep string in lowercase
String = String.lower()
for i in String:
if i == 'a' or i == 'e' or i == 'i' or i == 'o' or i == 'u':
#if True
count+=1
#check if any vowel found
if count == 0:
print('No vowels found')
else:
print('Total vowels are :' + str(count))
Output:
Enter the string :PrepInsta
Total vowels are :3
Result:The program to count the number of vowels in a string was successfully executed.
15)Aim:The program to check if a given key exists in a dictionary or not.
Description:
One common way to check if a key exists in a Python dictionary is by using the try/except block. This method involves trying to access the value of the key in question and catching a KeyError if it doesn't exist. In this example, we're attempting to access the value of the key 'pear' in the dictionary my_dict.
Program:
# Create a dictionary 'd' with key-value pairs.
d = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
# Define a function 'is_key_present' that takes an argument 'x'.
def is_key_present(x):
# Check if 'x' is a key in the dictionary 'd'.
if x in d:
# If 'x' is present in 'd', print a message indicating that the key is present.
print('Key is present in the dictionary')
else:
# If 'x' is not present in 'd', print a message indicating that the key is not present.
print('Key is not present in the dictionary')
# Call the 'is_key_present' function with the argument 5 to check if 5 is a key in the dictionary.
is_key_present(5)
# Call the 'is_key_present' function with the argument 9 to check if 9 is a key in the dictionary.
is_key_present(9)
Output:
Key is present in the dictionary
Key is not present in the dictionary
Result:The program to check if a given key exists in a dictionary or not was successfully completed.
16.Write a program to add a new key-value pair to existing dictionary. Aim:To write a program to add a new key-value pair to existing dictionary
Description:
Add a key value pair using update():The code initializes a dictionary dict and adds another dictionary dict1 using the update() method, merging their key-value pairs.
Then, it adds a new key-value pair ( newkey1='portal' ) to the dictionary by directly assigning it via update() . Add a key value pair using update()
Program:
my_dict = {'name': 'Alice', 'age': 30} new_key = 'city'
my_dict[new_key] = new_value print(my_dict)
Output: {'name':'Alice','age':30,'city':'Newyork'}
Result: The python program to add a new key-value pair to existing dictionary was successfully executed.
17)Aim:The program to sum all the items in a given dictionary.
Description:
Adding Values Using the setdefault() Method
In this method, we use the setdefault() method to add multiple values to a key. If there is a particular key already present in the dictionary, then this function adds the values passed to the key.
Program:
# Python3 Program to find sum of
# all items in a Dictionary
# Function to print sum
def returnSum(myDict):
list = []
for i in myDict:
list.append(myDict[i])
final = sum(list)
return final
# Driver Function
dict = {'a': 100, 'b': 200, 'c': 300}
print("Sum :", returnSum(dict))
Output:
Sum : 600
18. Wrie a program to sort words in a file and put them in another file. The output file should have only lower-case words, so any upper-case words from source must be lowered
DESCRIPTION:
Copying the content of one file to another while transforming the text to uppercase can be easily done using Python’s file handling features. By reading the source file, converting its contents to uppercase and writing to a new file, you can achieve this efficiently. Let’s look at the definitions of some important functions that will be used:
open() - It is used to open a file in various modes like reading, write, append, both read and write.
write() - It is used to write a specified text to a file.
upper() - It is used to convert all the lowercase letters to uppercase letters of a string and finally returns it.
PROGRAM:
inputfile ="input.txt"
outputfile ="output.txt"
with open(inputfile, "r") as infile:
words=[]
for line in infile:
words.extend(line.split())
sortedwords=sorted(words)
with open(outputfile, "w") as outfile:
for word in sortedwords:
outfile.write(word + "\n")
print("File Successfully written")
INPUT FILE:
hello how are you?
what is your name?
OUTPUT
File Successfully written
OUTPUT FILE:
are
hello
how
is
name?
what
you?
Your
RESULT:The python programto sort words in afile and put them in another file was successfully executed.
19. Aim: Write a python program to print each line of a file in reverse order.
Description:
Open the file:
Use the open() function to open the desired text file in read mode ("r").
Read all lines into a list:
Employ the readlines() method of the file object to read all lines from the file and store them as individual strings within a list. Each string in this list will represent a line from the file, including the newline character (\n) if present.
Reverse the list of lines:
Utilize list slicing with a step of -1 ([::-1]) to create a new list containing the lines in reverse order. This operation effectively reverses the order of elements in the list.
Iterate and print:
Loop through the reversed list of lines and print each line. To prevent extra blank lines in the output, use the strip() method on each line to remove any trailing whitespace, including the newline character, before printing.
Program:
file_path = 'input.txt'
try:
with open(file_path, 'r') as file:
for line in file:
reversed_line = line.rstrip()[::-1]
print(reversed_line)
except FileNotFoundError:
print(f"Error: The file '{file_path}' was not found.")
except Exception as e:
print(f"An error occurred: {e}")
input file:
input.txt
Hi, Hello!
How are you?
What are you doing?
Output:
!olleH ,iH
?uoy era woH
?gnioduoy era tahW
Result:The python program to print each line of a file in reverse order has successfully completed.
20. Aim: Write a python to compute the number of characters, words and lines in a file.
Description:
To compute the number of characters, words, and lines in a file using Python, one can implement a function that iterates through the file's content.
Open the file: The file is opened in read mode ('r') using the with open(...) as file: statement. This ensures the file is properly closed even if errors occur.
Initialize counters: Variables for line_count, word_count, and char_count are initialized to zero.
Iterate through lines: A for loop iterates over each line in the opened file object.
Count lines: Inside the loop, line_count is incremented by 1 for each line processed.
Count characters: The len(line) function returns the number of characters in the current line, including newline characters (\n). This value is added to char_count.
Count words: The line.split() method is used to split the current line into a list of words, using whitespace as the default delimiter. The len() of this resulting list is then added to word_count.
Return counts: After processing all lines, the function returns the accumulated line_count, word_count, and char_count.
Program:
file_path = 'input.txt'
try:
with open(file_path, 'r') as file:
lines = file.readlines()
line_count = len(lines)
word_count = 0
char_count = 0
for line in lines:
word_count += len(line.split())
char_count += len(line)
print(f"Number of lines : {line_count}")
print(f"Number of words : {word_count}")
print(f"Number of characters: {char_count}")
except FileNotFoundError:
print(f"Error: The file '{file_path}' was not found.")
except Exception as e:
print(f"An error occurred: {e}")
input file:
input.txt
Hi, Hello!
How are you?
What are you doing?
Output:
Number of lines : 3
Number of words : 9
Number of characters: 43
Result:The python program to compute the number of characters, words and lines in a file has successfully completed.
21. Aim: Write a program to create,display ,append,insert and reverse the order of the items in the array.
Description:
In Python, arrays are typically represented using lists or the array module for more type-specific arrays. The following describes how to perform common operations on a list, which serves as a general-purpose array:
1. Create:
An array (list) is created by enclosing elements in square brackets [], separated by commas.
2. Display:
The contents of an array are displayed using the print() function.
3. Append:
The append() method adds a new element to the end of the array.
4. Insert:
The insert() method adds an element at a specified index. It takes two arguments: the index and the value to insert.
The reverse() method reverses the elements of the array in-place, meaning it modifies the original array directly.
Program:
from array import array
arr = array('i', [10, 20, 30, 40, 50])
print("Original array:")
print(arr.tolist())
arr.append(60)
print("\nAfter appending 60:")
print(arr.tolist())
arr.insert(2, 25)
print("\nAfter inserting 25 at index 2:")
print(arr.tolist())
arr.reverse()
print("\nAfter reversing the array:")
print(arr.tolist())
Output:
Original array:
[10, 20, 30, 40, 50]
After appending 60:
[10, 20, 30, 40, 50, 60]
After inserting 25 at index 2:
[10, 20, 25, 30, 40, 50, 60]
After reversing the array:
[60, 50, 40, 30, 25, 20, 10]
Result:The python program to create,display ,append,insert and reverse the order of the items in the array has successfully completed.
22. Aim: Write a program to add,transpose and multiply two matrices.
Description:
Matrix operations in Python can be implemented using nested lists or, more efficiently, using the NumPy library.
1. Matrix Addition:
Matrix addition involves adding corresponding elements of two matrices of the same dimensions.
2. Matrix Transposition:
Matrix transposition involves swapping the rows and columns of a matrix, meaning the element at (i, j) in the original matrix becomes the element at (j, i) in the transposed matrix.
3. Matrix Multiplication:
Matrix multiplication requires that the number of columns in the first matrix equals the number of rows in the second matrix. The resulting matrix will have dimensions equal to the number of rows in the first matrix by the number of columns in the second matrix. Each element of the resulting matrix is the dot product of a row from the first matrix and a column from the second matrix.
Program:
def display(matrix):
for row in matrix:
print(row)
def add_matrices(A, B):
result = []
for i in range(len(A)):
row = []
for j in range(len(A[0])):
row.append(A[i][j] + B[i][j])
result.append(row)
return result
def transpose_matrix(M):
rows, cols = len(M), len(M[0])
return [[M[j][i] for j in range(rows)] for i in range(cols)]
def multiply_matrices(A, B):
result = []
for i in range(len(A)):
row = []
for j in range(len(B[0])):
sum = 0
for k in range(len(A[0])):
sum += A[i][k] * B[k][j]
row.append(sum)
result.append(row)
return result
# matrices
A = [
[1, 2, 3],
[4, 5, 6]
]
B = [
[7, 8, 9],
[10, 11, 12]
]
C = [
[1, 4],
[2, 5],
[3, 6]
]
print("Matrix A:")
display(A)
print("\nMatrix B:")
display(B)
# Matrix Addition
print("\nAddition of A and B:")
added = add_matrices(A, B)
display(added)
# Transpose of A
print("\nTranspose of Matrix A:")
transpose = transpose_matrix(A)
display(transpose)
# Multiplication
print("\nMatrix C (for multiplication):")
display(C)
print("\nMultiplication of A and C:")
product = multiply_matrices(A, C)
display(product)
Output:
Matrix A:
[1, 2, 3]
[4, 5, 6]
Matrix B:
[7, 8, 9]
[10, 11, 12]
Addition of A and B:
[8, 10, 12]
[14, 16, 18]
Transpose of Matrix A:
[1, 4]
[2, 5]
[3, 6]
Matrix C (for multiplication):
[1, 4]
[2, 5]
[3, 6]
Multiplication of A and C:
[14, 32]
[32, 77]
Result: The python program to add, transpose and multiply two matrices has successfully completed.
23. Aim: Write a python program to create a class that represents a shape. Include methods to calculate its area and perimeter. Implement subclasses for different shapes like circle, triangle, and square.
Description:
A Python class structure can be implemented to represent a Shape with subclasses for specific geometric shapes like Circle, Triangle, and Square. This structure utilizes inheritance and polymorphism to provide a consistent interface for calculating area and perimeter across different shapes.
This abstract base class defines the common interface for all shapes. It should include abstract methods calculate_area() and calculate_perimeter(), which are meant to be implemented by its subclasses. The abc module and @abstractmethod decorator from Python's abc library can be used to enforce this.
Each specific shape (Circle, Triangle, Square) will inherit from the Shape class and provide concrete implementations for the calculate_area() and calculate_perimeter() methods based on their respective geometric formulas.
Program:
import math
# Base class
class Shape:
def area(self):
raise NotImplementedError("Area method not implemented!")
def perimeter(self):
raise NotImplementedError("Perimeter method not implemented!")
# Subclass: Circle
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * self.radius ** 2
def perimeter(self):
return 2 * math.pi * self.radius
# Subclass: Square
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
def perimeter(self):
return 4 * self.side
# Subclass: Triangle (using sides and Heron's formula)
class Triangle(Shape):
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def area(self):
s = (self.a + self.b + self.c) / 2
return math.sqrt(s * (s - self.a) * (s - self.b) * (s - self.c))
def perimeter(self):
return self.a + self.b + self.c
circle = Circle(5)
print("Circle: Area =", round(circle.area(), 2), ", Perimeter =", round(circle.perimeter(), 2))
square = Square(4)
print("Square: Area =", square.area(), ", Perimeter =", square.perimeter())
triangle = Triangle(3, 4, 5)
print("Triangle: Area =", round(triangle.area(), 2), ", Perimeter =", triangle.perimeter())
Output:
Circle: Area = 78.54 , Perimeter = 31.42
Square: Area = 16 , Perimeter = 16
Triangle: Area = 6.0 , Perimeter = 12
Result: The python program to create a class that represents a shape. Include methods to calculate its area and perimeter. Implement subclasses for different shapes like circle, triangle, and square has successfully completed.
24
import json
def check_complex_json(json_str):
try:
data = json.loads(json_str)
return any(isinstance(i, (dict, list)) for i in (data.values() if isinstance(data, dict) else data))
except json.JSONDecodeError:
return False
json_str = '{"name": "John", "address": {"city": "New York", "zipcode": 10001}}'
print("The JSON contains a complex object." if check_complex_json(json_str) else "The JSON does not contain a complex object.")
output
The JSON contains a complex object.
25
import numpy as np
array_from_list = np.array([1, 2, 3, 4])
array_2d = np.array([[1, 2, 3], [4, 5, 6]])
zeros_array = np.array(np.zeros((2, 3)))
ones_array = np.array(np.ones((3, 2)))
range_array = np.array(np.arange(0, 10, 2))
linspace_array = np.array(np.linspace(0, 1, 5))
identity_matrix = np.array(np.eye(3))
random_array = np.array(np.random.rand(2, 2))
print(array_from_list, array_2d, zeros_array, ones_array, range_array, linspace_array, identity_matrix, random_array)
Output
[1 2 3 4] [[1 2 3]
[4 5 6]] [[0. 0. 0.]
[0. 0. 0.]] [[1. 1.]
[1. 1.]
[1. 1.]] [0 2 4 6 8] [0. 0.25 0.5 0.75 1. ] [[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]] [[0.39927304 0.46015422]
[0.64270914 0.52463068]]
26
import numpy as np
array_from_list = np.array([1, 2, 3, 4])
array_2d = np.array([[1, 2, 3], [4, 5, 6]])
zeros_array = np.array(np.zeros((2, 3)))
ones_array = np.array(np.ones((3, 2)))
range_array = np.array(np.arange(0, 10, 2))
linspace_array = np.array(np.linspace(0, 1, 5))
identity_matrix = np.array(np.eye(3))
random_array = np.array(np.random.rand(2, 2))
print(array_from_list.ndim, array_from_list.shape, array_from_list.size, array_from_list.dtype)
print(array_2d.ndim, array_2d.shape, array_2d.size, array_2d.dtype)
print(zeros_array.ndim, zeros_array.shape, zeros_array.size, zeros_array.dtype)
print(ones_array.ndim, ones_array.shape, ones_array.size, ones_array.dtype)
print(range_array.ndim, range_array.shape, range_array.size, range_array.dtype)
print(linspace_array.ndim, linspace_array.shape, linspace_array.size, linspace_array.dtype)
print(identity_matrix.ndim, identity_matrix.shape, identity_matrix.size, identity_matrix.dtype)
print(random_array.ndim, random_array.shape, random_array.size, random_array.dtype)
Output
1 (4,) 4 int64
2 (2, 3) 6 int64
2 (2, 3) 6 float64
2 (3, 2) 6 float64
1 (5,) 5 int64
1 (5,) 5 float64
2 (3, 3) 9 float64
2 (2, 2) 4 float64
27
import numpy as np
array_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
slice_example = array_2d[0:2, 1:3]
int_indexing_example = array_2d[[0, 2], [1, 2]]
mask = array_2d > 5
boolean_indexing_example = array_2d[mask]
print("Sliced array:\n", slice_example)
print("Integer indexed elements:", int_indexing_example)
print("Boolean indexed elements:", boolean_indexing_example)
Output
Sliced array:
[[2 3]
[5 6]]
Integer indexed elements: [2 9]
Boolean indexed elements: [6 7 8 9]
28
import numpy as np
array = np.array([1, 2, 3, 4, 5])
min_value = np.min(array)
max_value = np.max(array)
sum_value = np.sum(array)
cumsum_value = np.cumsum(array)
print("Min:", min_value)
print("Max:", max_value)
print("Sum:", sum_value)
print("Cumulative Sum:", cumsum_value)
Output
Min: 1
Max: 5
Sum: 15
Cumulative Sum: [ 1 3 6 10 15]
29
import pandas as pd
data = {
'A': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'B': [11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
'C': [21, 22, 23, 24, 25, 26, 27, 28, 29, 30],
'D': [31, 32, 33, 34, 35, 36, 37, 38, 39, 40],
'E': [41, 42, 43, 44, 45, 46, 47, 48, 49, 50]
}
df = pd.DataFrame(data)
df_head = df.head()
row_selection = df.iloc[2]
col_selection = df['B']
filtered_df = df[df['A'] > 5]
print(df_head)
print(row_selection)
print(col_selection)
print(filtered_df)
Output
A B C D E
0 1 11 21 31 41
1 2 12 22 32 42
2 3 13 23 33 43
3 4 14 24 34 44
4 5 15 25 35 45
A 3
B 13
C 23
D 33
E 43
Name: 2, dtype: int64
0 11
1 12
2 13
3 14
4 15
5 16
6 17
7 18
8 19
9 20
Name: B, dtype: int64
A B C D E
5 6 16 26 36 46
6 7 17 27 37 47
7 8 18 28 38 48
8 9 19 29 39 49
9 10 20 30 40 50
30
import pandas as pd
import matplotlib.pyplot as plt
data = {
'A': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'B': [11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
'C': [21, 22, 23, 24, 25, 26, 27, 28, 29, 30],
'D': [31, 32, 33, 34, 35, 36, 37, 38, 39, 40],
'E': [41, 42, 43, 44, 45, 46, 47, 48, 49, 50]
}
df = pd.DataFrame(data)
x = df['A']
y = df['B']
plt.scatter(x, y)
plt.title("Scatter Plot: A vs B")
plt.xlabel("A")
plt.ylabel("B")
plt.show()
y_squared = df['B'] ** 2
plt.plot(x, y_squared)
plt.title("Plot: A vs B^2")
plt.xlabel("A")
plt.ylabel("B^2")
plt.show()
output
31
import numpy as np
array1 = np.array([1, 2, 3, 4, 5])
array2 = np.array([6, 7, 8, 9, 10])
addition_result = array1 + array2
multiplication_result = array1 * array2
print("Addition Result:", addition_result)
print("Multip
lication Result:", multiplication_result)
Output
Addition Result: [ 7 9 11 13 15]
Multiplication Result: [ 6 14 24 36 50]
32
import pandas as pd
df1 = pd.DataFrame({
'ID': [1, 2, 3, 4],
'Name': ['Alice', 'Bob', 'Charlie', 'David']
})
df2 = pd.DataFrame({
'ID': [3, 4, 5, 6],
'Age': [25, 30, 35, 40]
})
merged_df = pd.merge(df1, df2, on='ID')
print(merged_df)
Output
ID Name Age
0 3 Charlie 25
1 4 David 30
0 Comments