0% found this document useful (0 votes)
17 views

5 WEEK Python Programs

Uploaded by

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

5 WEEK Python Programs

Uploaded by

AKHIL Garena
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

24)Python program to check whether a JSON string contains complex object or not

AIM: Python program to check whether a JSON string contains complex object or not

PROGRAM:

import json

def is_complex_object(data):

"""Check if the given data is a complex object."""

if isinstance(data, dict):

# If it's a dictionary, check for nested structures

for key, value in data.items():

if isinstance(value, (dict, list)):

return True

elif isinstance(data, list):

# If it's a list, check for nested structures

for item in data:

if isinstance(item, (dict, list)):

return True

return False

def check_json_complexity(json_string):

"""Check whether a JSON string contains complex objects."""

try:

data = json.loads(json_string)

return is_complex_object(data)

except json.JSONDecodeError:

print("Invalid JSON string.")

return False

# Example usage
json_string1 = '{"name": "Alice", "age": 30, "details": {"hobbies": ["reading", "hiking"]}}'

json_string2 = '["apple", "banana", "cherry"]'

json_string3 = '{"name": "Bob", "age": 25}'

print(check_json_complexity(json_string1)) # True (contains a complex object)

print(check_json_complexity(json_string2)) # False (simple array)

print(check_json_complexity(json_string3)) # False (simple object)

OUTPUT:

True

False

False

RESULT: Python program for checked a JSON string contains complex object or not is successfully
executed.

25)Python Program to demonstrate NumPy arrays creation using array () function.

AIM: Python Program to demonstrate NumPy arrays creation using array () function.

PROGRAM:

import numpy as np

# Creating a 1D array (a simple list)

array_1d = np.array([1, 2, 3, 4, 5])

print("1D Array:")

print(array_1d)

# Creating a 2D array (a list of lists)

array_2d = np.array([[1, 2, 3], [4, 5, 6]])

print("\n2D Array:")

print(array_2d)
# Creating a 3D array (a list of lists of lists)

array_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])

print("\n3D Array:")

print(array_3d)

# Creating an array of floats

float_array = np.array([1.1, 2.2, 3.3])

print("\nFloat Array:")

print(float_array)

# Creating an array with a specified data type

int_array = np.array([1, 2, 3], dtype=np.int32)

print("\nInteger Array with dtype int32:")

print(int_array)

# Creating a multi-dimensional array with zeros

zeros_array = np.array([[0, 0, 0], [0, 0, 0]])

print("\nArray of Zeros:")

print(zeros_array)

# Creating a multi-dimensional array with ones

ones_array = np.array([[1, 1, 1], [1, 1, 1]])

print("\nArray of Ones:")

print(ones_array)

OUTPUT:

1D Array:

[1 2 3 4 5]
2D Array:

[[1 2 3]

[4 5 6]]

3D Array:

[[[1 2]

[3 4]]

[[5 6]

[7 8]]]

Float Array:

[1.1 2.2 3.3]

Integer Array with dtype int32:

[1 2 3]

Array of Zeros:

[[0 0 0]

[0 0 0]]

Array of Ones:

[[1 1 1]

[1 1 1]]

RESULT: : Python Program to demonstrate NumPy arrays creation using array () function is successfully
executed.

26) python program to demonstrate use of ndim, shape, size, dtype

AIM: Python program to demonstrate use of ndim, shape, size, dtype

PROGRAM:
import numpy as np

# Creating a 1D array

array_1d = np.array([1, 2, 3, 4, 5])

print("1D Array:")

print(array_1d)

print("Number of dimensions (ndim):", array_1d.ndim)

print("Shape:", array_1d.shape)

print("Size (number of elements):", array_1d.size)

print("Data type (dtype):", array_1d.dtype)

print()

# Creating a 2D array

array_2d = np.array([[1, 2, 3], [4, 5, 6]])

print("2D Array:")

print(array_2d)

print("Number of dimensions (ndim):", array_2d.ndim)

print("Shape:", array_2d.shape)

print("Size (number of elements):", array_2d.size)

print("Data type (dtype):", array_2d.dtype)

print()

# Creating a 3D array

array_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])

print("3D Array:")

print(array_3d)

print("Number of dimensions (ndim):", array_3d.ndim)

print("Shape:", array_3d.shape)

print("Size (number of elements):", array_3d.size)


print("Data type (dtype):", array_3d.dtype)

print()

# Creating an array with a specific data type

float_array = np.array([1.1, 2.2, 3.3], dtype=np.float64)

print("Float Array:")

print(float_array)

print("Number of dimensions (ndim):", float_array.ndim)

print("Shape:", float_array.shape)

print("Size (number of elements):", float_array.size)

print("Data type (dtype):", float_array.dtype)

OUTPUT:

1D Array:

[1 2 3 4 5]

Number of dimensions (ndim): 1

Shape: (5,)

Size (number of elements): 5

Data type (dtype): int64

2D Array:

[[1 2 3]

[4 5 6]]

Number of dimensions (ndim): 2

Shape: (2, 3)

Size (number of elements): 6

Data type (dtype): int64

3D Array:
[[[1 2]

[3 4]]

[[5 6]

[7 8]]]

Number of dimensions (ndim): 3

Shape: (2, 2, 2)

Size (number of elements): 8

Data type (dtype): int64

Float Array:

[1.1 2.2 3.3]

Number of dimensions (ndim): 1

Shape: (3,)

Size (number of elements): 3

Data type (dtype): float64

RESULT:

27) Python program to demonstrate basic slicing, integer and Boolean indexing.

AIM: A Python program to demonstrate basic slicing, integer and Boolean indexing.

PROGRAM:

import numpy as np

# Creating a sample 2D array

array_2d = np.array([[10, 20, 30, 40],

[50, 60, 70, 80],

[90, 100, 110, 120]])

print("Original 2D Array:")
print(array_2d)

# Basic Slicing

print("\nBasic Slicing (first two rows, last two columns):")

sliced_array = array_2d[:2, 2:]

print(sliced_array)

# Integer Indexing

print("\nInteger Indexing (selecting specific elements):")

# Selecting the element at (1, 2) and (2, 1)

integer_indexed_array = array_2d[[1, 2], [2, 1]]

print(integer_indexed_array)

# Boolean Indexing

print("\nBoolean Indexing (selecting elements greater than 60):")

boolean_mask = array_2d > 60

boolean_indexed_array = array_2d[boolean_mask]

print(boolean_indexed_array)

# Boolean Indexing with condition

print("\nBoolean Indexing with condition (selecting elements < 100):")

condition_mask = array_2d < 100

condition_indexed_array = array_2d[condition_mask]

print(condition_indexed_array)

OUTPUT:

Original 2D Array:

[[ 10 20 30 40]

[ 50 60 70 80]

[ 90 100 110 120]]


Basic Slicing (first two rows, last two columns):

[[30 40]

[70 80]]

Integer Indexing (selecting specific elements):

[ 70 100]

Boolean Indexing (selecting elements greater than 60):

[ 70 80 90 100 110 120]

Boolean Indexing with condition (selecting elements < 100):

[10 20 30 40 50 60 70 80 90]

RESULT:

28) Python program to find min, max, sum, cumulative sum of array

AIM: A Python program to find min, max, sum, cumulative sum of array

PROGRAM:

import numpy as np

# Creating a sample array

array = np.array([10, 20, 30, 40, 50])

print("Original Array:")

print(array)

# Finding the minimum value

min_value = np.min(array)
print("\nMinimum Value:")

print(min_value)

# Finding the maximum value

max_value = np.max(array)

print("\nMaximum Value:")

print(max_value)

# Finding the sum of the array elements

sum_value = np.sum(array)

print("\nSum of Array Elements:")

print(sum_value)

# Finding the cumulative sum of the array

cumulative_sum = np.cumsum(array)

print("\nCumulative Sum of Array:")

print(cumulative_sum)

OUTPUT:

Original Array:

[10 20 30 40 50]

Minimum Value:

10

Maximum Value:

50

Sum of Array Elements:

150
Cumulative Sum of Array:

[ 10 30 60 100 150]

RESULT:

29) Create a dictionary with at least five keys and each key represent value as a list where this list contains
at least ten values and convert this dictionary as a pandas data frame and explore the data through the
data frame as follows:

a) Apply head () function to the pandas data frame

b) Perform various data selection operations on Data Frame

a)AIM: Apply head () function to the pandas data frame

PROGRAM: import pandas as pd

# Creating a dictionary with 5 keys, each containing a list of 10 values

data = {

'Product': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'],

'Price': [10.99, 12.50, 8.99, 14.99, 7.50, 20.00, 15.75, 9.99, 13.50, 11.25],

'Quantity': [100, 150, 200, 120, 180, 90, 50, 300, 250, 80],

'Category': ['Electronics', 'Electronics', 'Home', 'Home', 'Clothing',

'Clothing', 'Electronics', 'Home', 'Clothing', 'Electronics'],

'Rating': [4.5, 4.0, 3.5, 4.7, 4.2, 3.9, 4.8, 4.1, 3.7, 4.6]

# Converting the dictionary to a Pandas DataFrame

df = pd.DataFrame(data)

# a) Apply head() function to the DataFrame

print("DataFrame head:")

print(df.head())
OUTPUT:

DataFrame head:

Product Price Quantity Category Rating

A 10.99 100 Electronics 4.5

B 12.50 150 Electronics 4.0

C 8.99 200 Home 3.5

D 14.99 120 Home 4.7

E 7.50 180 Clothing 4.2

b) AIM:Perform various data selection operations on Data Frame

PROGRAM:

import pandas as pd

# Creating a dictionary with 5 keys, each containing a list of 10 values

data = {

'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve', 'Frank', 'Grace', 'Hannah', 'Isaac', 'Jack'],

'Age': [24, 30, 22, 29, 25, 35, 27, 32, 28, 31],

'Salary': [50000, 60000, 45000, 70000, 52000, 80000, 75000, 58000, 62000, 90000],

'Department': ['HR', 'IT', 'Finance', 'IT', 'HR', 'Finance', 'HR', 'IT', 'Finance', 'IT'],

'Experience': [2, 5, 1, 4, 3, 8, 6, 5, 7, 9]

# Converting the dictionary to a Pandas DataFrame

df = pd.DataFrame(data)

# Displaying the DataFrame

print("DataFrame:")

print(df)
# a) Applying head() function to the DataFrame

print("\nDataFrame head:")

print(df.head())

# b) Various data selection operations

# Selecting a single column

print("\nSelecting the 'Name' column:")

print(df['Name'])

# Selecting multiple columns

print("\nSelecting 'Name' and 'Salary' columns:")

print(df[['Name', 'Salary']])

# Selecting rows by index

print("\nSelecting the first three rows:")

print(df.iloc[:3])

# Selecting rows where 'Age' is greater than 30

print("\nRows where 'Age' is greater than 30:")

print(df[df['Age'] > 30])

# Selecting specific rows and columns

print("\nSelecting rows 1 to 3 for columns 'Name' and 'Department':")

print(df.loc[1:3, ['Name', 'Department']])

# Selecting rows where 'Department' is 'IT'

print("\nRows where 'Department' is 'IT':")


print(df[df['Department'] == 'IT'])

OUTPUT:

DataFrame:

Name Age Salary Department Experience

0 Alice 24 50000 HR 2

1 Bob 30 60000 IT 5

2 Charlie 22 45000 Finance 1

3 David 29 70000 IT 4

4 Eve 25 52000 HR 3

5 Frank 35 80000 Finance 8

6 Grace 27 75000 HR 6

7 Hannah 32 58000 IT 5

8 Isaac 28 62000 Finance 7

9 Jack 31 90000 IT 9

DataFrame head:

Name Age Salary Department Experience

0 Alice 24 50000 HR 2

1 Bob 30 60000 IT 5

2 Charlie 22 45000 Finance 1

3 David 29 70000 IT 4

4 Eve 25 52000 HR 3

Selecting the 'Name' column:

0 Alice

1 Bob

2 Charlie

3 David

4 Eve
5 Frank

6 Grace

7 Hannah

8 Isaac

9 Jack

Name: Name, dtype: object

Selecting 'Name' and 'Salary' columns:

Name Salary

0 Alice 50000

1 Bob 60000

2 Charlie 45000

3 David 70000

4 Eve 52000

5 Frank 80000

6 Grace 75000

7 Hannah 58000

8 Isaac 62000

9 Jack 90000

Selecting the first three rows:

Name Age Salary Department Experience

0 Alice 24 50000 HR 2

1 Bob 30 60000 IT 5

2 Charlie 22 45000 Finance 1

Rows where 'Age' is greater than 30:

Name Age Salary Department Experience

5 Frank 35 80000 Finance 8


7 Hannah 32 58000 IT 5

9 Jack 31 90000 IT 9

Selecting rows 1 to 3 for columns 'Name' and 'Department':

Name Department

1 Bob IT

2 Charlie Finance

3 David IT

Rows where 'Department' is 'IT':

Name Age Salary Department Experience

1 Bob 30 60000 IT 5

3 David 29 70000 IT 4

7 Hannah 32 58000 IT 5

9 Jack 31 90000 IT 9

RESULT: The above program is successfully executed

30)select any two columns from the above data frame ,observe the change in
one attribute with respect to other attribute with scatter and plot operations
in matplotlib

Aim : write a python program to select any two columns from the above data
frame ,observe the change in one attribute with respect to other attribute with
scatter and plot operations in matplotlib

Program:
import pandas as pd
import matplotlib.pyplot as plt

# Sample DataFrame creation


data = {
'Height': [150, 160, 170, 180, 190],
'Weight': [50, 60, 70, 80, 90],
'Age': [25, 30, 35, 40, 45]
}

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

# Select two columns to analyze


x_column = 'Height' # Change this to your desired x-axis column
y_column = 'Weight' # Change this to your desired y-axis column

# Create a scatter plot


plt.figure(figsize=(10, 6))
plt.scatter(df[x_column], df[y_column], color='blue', label='Data Points', s=100)
plt.title(f'Scatter Plot of {y_column} vs {x_column}')
plt.xlabel(x_column)
plt.ylabel(y_column)
plt.legend()
plt.grid(True)
plt.show()

# Optionally, create a line plot to show the trend


plt.figure(figsize=(10, 6))
plt.plot(df[x_column], df[y_column], marker='o', linestyle='-', color='orange',
label='Trend Line')
plt.title(f'Line Plot of {y_column} vs {x_column}')
plt.xlabel(x_column)
plt.ylabel(y_column)
plt.legend()
plt.grid(True)
plt.show()

output:
Result : The above select any two columns from the above data frame
,observe the change in one attribute with respect to other attribute with
scatter and plot operations in matplotlib program is successfully executed.
BEYOND SYLLABUS
1) Write a program to find a factorial of a given number
AIM: To write a program factorial of a given number.
PROGRAM:
def factorial_iterative(n):
if n < 0:
return "Factorial is not defined for negative numbers."
result = 1
for i in range(1, n + 1):
result *= i
return result
number = int(input("Enter a number to find its factorial: "))
print(f"The factorial of {number} is {factorial_iterative(number)}")
OUTPUT
Enter a number to find its factorial: 5
The factorial of 5 is 120

RESULT: Factorial of a given number program is successfully Executed.


2)Write a program to check given number is perfect number or not
AIM:TO write a program to check given number is perfect number or not

PROGRAM:

def is_perfect_number(n):
if n < 1:

return False # Perfect numbers are positive integers

# Calculate the sum of proper divisors

sum_of_divisors = 0

for i in range(1, n):

if n % i == 0:

sum_of_divisors += i

# Check if the sum of divisors equals the number

return sum_of_divisors == n

# Example usage

number = int(input("Enter a number to check if it is a perfect number: "))

if is_perfect_number(number):

print(f"{number} is a perfect number.")

else:

print(f"{number} is not a perfect number.")

OUTPUT
Enter a number to check if it is a perfect number: 6

6 is a perfect number.

RESULT: The python program to check given number is perfect number


or not is sucessfully Executed

You might also like