Monday, 31 March 2025

Python Coding Challange - Question With Answer(01010425)

 


Step-by-step Execution:

  1. try block execution:

    • The try block contains print("Python").

    • Since print("Python") does not cause any error, the statement executes successfully.

    • Output: Python

  2. except block execution:

    • The except block runs only if an exception occurs in the try block.

    • Since no exception occurs, this block is skipped.

  3. Final statement:

    • The next line after the try-except block is print("Anaconda"), which executes normally.

    • Output: Anaconda

Final Output:


Python
Anaconda

Key Takeaways:

  • The except block is only executed if an error occurs in the try block.

  • Since print("Python") executes without an error, the except block is skipped.

  • The program continues executing normally after the try-except block.


Check Now Python Libraries for Civil Engineering

https://pythonclcoding.gumroad.com/l/feegvl

Tundra Tapestry Pattern using Python

 


import matplotlib.pyplot as plt

import numpy as np

patterns=patterns = ['/','\\','|','-','+','x','o','O','.','*','///','\\\\','|||','--','++','xx','oo','OO','..','**']

while len(patterns)<50:

    patterns.extend(patterns)

patterns=patterns[:50]

x=np.arange(1,51)

y=np.random.randint(10,100,size=50)

fig,ax=plt.subplots(figsize=(8,8))

tundra_colors=['#A8D5BA','#B5E2CD','#CDE6D0','#D9EAD3','#E5F5E0']

for i in range(50):

    ax.bar(x[i],y[i],hatch=patterns[i],color=tundra_colors[i%5],edgecolor='black')

ax.set_xlabel('Index')

ax.set_ylabel('Value')

ax.set_title('Tundra Tapestry Pattern')

plt.show()

#source code --> clcoding.com 

Code Explanation:

1. Importing Libraries

import numpy as np

import matplotlib.pyplot as plt

numpy: Used for generating numerical data, especially arrays and random numbers.

matplotlib.pyplot: A popular Python library for creating visualizations, including bar plots.

 2. Defining Patterns

patterns = ['/', '\\', '|', '-', '+', 'x', 'o', 'O', '.', '*', '///', '\\\\', '|||', '--', '++', 'xx', 'oo', 'OO', '..', '**']

A list of hatch patterns (textures used to fill bars).

These are commonly used in visualizations for differentiating bars in black-and-white or colorblind-friendly charts.

 3. Extending Patterns to 50

while len(patterns) < 50:

    patterns.extend(patterns)

patterns = patterns[:50]

If the list contains fewer than 50 patterns, it repeats the list using extend().

patterns[:50] ensures exactly 50 patterns by slicing the list.

 4. Generating Data

x = np.arange(1, 51)

y = np.random.randint(10, 100, size=50)

x: A sequence of numbers from 1 to 50 representing the x-axis values (indices).

y: 50 random integers between 10 and 100 for the y-axis (bar heights).

 5. Creating the Figure and Axis

fig, ax = plt.subplots(figsize=(12, 8))

fig represents the figure (the entire visualization space).

ax is the plotting area where the bars are drawn.

figsize=(12, 8) specifies the size of the figure in inches.

 6. Defining Tundra Colors

tundra_colors = ['#A8D5BA', '#B5E2CD', '#CDE6D0', '#D9EAD3', '#E5F5E0']

A soft, pastel color palette representing tundra landscapes.

Colors are in hex format (#RRGGBB).

 7. Plotting Bars

for i in range(50):

    ax.bar(x[i], y[i], hatch=patterns[i], color=tundra_colors[i % 5], edgecolor='black')

A for loop iterates 50 times to plot each bar.

 ax.bar() creates a bar using:

 x[i] → Position on the x-axis.

 y[i] → Height of the bar.

 hatch=patterns[i] → Texture of the bar.

 color=tundra_colors[i % 5] → Cycles through the 5 tundra colors using the modulo operator.

 edgecolor='black' → Black border for contrast.

 8. Adding Labels and Title

ax.set_xlabel('Index')

ax.set_ylabel('Value')

ax.set_title('Tundra Tapestry: 50 Unique Pattern Plot using Matplotlib')

ax.set_xlabel() and ax.set_ylabel() label the x and y axes.

ax.set_title() gives the plot a descriptive title.

 9. Displaying the Plot

plt.show()

This renders and displays the completed plot using matplotlib.

 


3D Wireframe Grid using Python

 

import numpy as np

import matplotlib.pyplot as plt

from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure(figsize=(10, 10))

ax = fig.add_subplot(111, projection='3d')

vertices = np.array([

    [0, 0, 0],

    [1, 0, 0],

    [1, 1, 0],

    [0, 1, 0],

    [0, 0, 1],

    [1, 0, 1],

    [1, 1, 1],

    [0, 1, 1]

])

edges = [

    [0, 1], [1, 2], [2, 3], [3, 0],  

    [4, 5], [5, 6], [6, 7], [7, 4], 

    [0, 4], [1, 5], [2, 6], [3, 7]   

]

for edge in edges:

    ax.plot3D(*zip(*vertices[edge]),color="b",linewidth=2)

ax.set_title("3D wireframe Grid",fontsize=20)

ax.set_xlabel('X')

ax.set_ylabel('Y')

ax.set_zlabel('Z')

ax.set_box_aspect([1,1,1])

plt.show()

#source code --> clcoding.com 

Code Explanation:

1. Importing Required Libraries

import numpy as np

import matplotlib.pyplot as plt

from mpl_toolkits.mplot3d import Axes3D

numpy: This is used for efficient numerical operations, especially creating arrays. In this case, it is used to store the vertices of the 3D wireframe.

 matplotlib.pyplot: This is a plotting library used for creating static, animated, and interactive visualizations. It is used here for generating the plot.

 mpl_toolkits.mplot3d.Axes3D: This is an extension of the matplotlib library that enables 3D plotting. It allows us to create 3D visualizations like wireframes.

 2. Creating the Figure and Axes

fig = plt.figure(figsize=(10, 10))

ax = fig.add_subplot(111, projection='3d')

plt.figure(figsize=(10, 10)): This creates a figure of size 10x10 inches. The figsize argument sets the overall size of the plot.

 fig.add_subplot(111, projection='3d'): This adds a 3D subplot to the figure, meaning we will be plotting 3D data. The '111' means "1x1 grid, 1st subplot" (which is just one subplot in this case). The projection='3d' argument specifies that we want a 3D plot.

 3. Defining the Cube's Vertices

vertices = np.array([

    [0, 0, 0],

    [1, 0, 0],

    [1, 1, 0],

    [0, 1, 0],

    [0, 0, 1],

    [1, 0, 1],

    [1, 1, 1],

    [0, 1, 1]

])

Here, vertices is a NumPy array containing the 8 vertices of a cube. Each vertex is represented by its (x, y, z) coordinates in 3D space.

 [0, 0, 0] is the origin, the starting point.

 The other vertices define the corners of a unit cube, with each coordinate either being 0 or 1 to form the edges of the cube.

 

4. Defining the Cube's Edges

edges = [

    [0, 1], [1, 2], [2, 3], [3, 0],  # Bottom square

    [4, 5], [5, 6], [6, 7], [7, 4],  # Top square

    [0, 4], [1, 5], [2, 6], [3, 7]   # Vertical connections between top and bottom

]

edges defines the connections (or lines) between the vertices of the cube. Each pair of indices (e.g., [0, 1], [1, 2]) refers to the vertices that should be connected.

 The first four edges form the bottom square of the cube.

 The next four edges form the top square.

 The last four edges are the vertical connections that connect the top and bottom squares, forming the sides of the cube.

 5. Plotting the Cube's Wireframe

for edge in edges:

    ax.plot3D(*zip(*vertices[edge]), color="b", linewidth=2)

for edge in edges: This loop iterates over all the edges defined in the edges list.

vertices[edge]: This selects the pair of vertices from the vertices array using the indices specified in the edges list.

 zip(*vertices[edge]): The zip function unpacks the vertices and prepares them in the format required for plotting (separating the x, y, and z coordinates).

 ax.plot3D(...): This function plots the 3D lines connecting the pairs of vertices for each edge. It takes the x, y, and z coordinates of the two vertices and plots the line between them.

 color="b": This sets the color of the lines to blue.

 linewidth=2: This sets the thickness of the lines to 2.

 6. Setting the Title and Labels

ax.set_title("3D Wireframe Grid", fontsize=20)

ax.set_xlabel('X')

ax.set_ylabel('Y')

ax.set_zlabel('Z')

ax.set_title("3D Wireframe Grid", fontsize=20): This sets the title of the plot to "3D Wireframe Grid" with a font size of 20.

 ax.set_xlabel('X'): This labels the x-axis as 'X'.

 ax.set_ylabel('Y'): This labels the y-axis as 'Y'.

 ax.set_zlabel('Z'): This labels the z-axis as 'Z'.

 7. Setting the Aspect Ratio

ax.set_box_aspect([1, 1, 1])

ax.set_box_aspect([1, 1, 1]): This ensures that the aspect ratio of the plot is equal in all three dimensions. This makes sure the cube looks proportionate, rather than distorted, regardless of the plot window size.

 8. Displaying the Plot

plt.show()

Python Coding challenge - Day 422| What is the output of the following Python Code?

 


Code Explanation:

Importing NumPy:
import numpy as np
np is a common alias for NumPy, making it easier to reference.

Creating Vectors:
vector1 = np.array([1, 2, 3])
vector2 = np.array([4, 5, 6])
np.array() is used to create NumPy arrays.

vector1 is [1, 2, 3] and vector2 is [4, 5, 6].

Calculating the Dot Product:
dot_product = np.dot(vector1, vector2)
The dot product of two vectors 
๐‘Ž⋅๐‘
a⋅b is calculated using the formula:
(1⋅4)+(2⋅5)+(3⋅6)=4+10+18=32

Printing the Result:
print(dot_product)
This prints the result, which is 32.

Final Output:

32

Python Coding challenge - Day 421| What is the output of the following Python Code?


 


Code Explanation:

1. Importing the JSON Module

import json

This imports Python's built-in json module, which is used to work with JSON data (JavaScript Object Notation).

You can convert Python dictionaries to JSON format and vice versa using this module.

2. Creating a Dictionary

data = {'a': 1, 'b': 2}

A simple Python dictionary named data is created with two key-value pairs:

'a': 1

'b': 2

3. Writing the Dictionary to a JSON File

with open('data.json', 'w') as file:

    json.dump(data, file)

open('data.json', 'w'):

Opens (or creates) a file named data.json in write mode ('w').

If the file exists, it will overwrite the contents.

json.dump(data, file):

Converts the Python dictionary (data) into a JSON formatted string and writes it to the file.

Content of data.json after this step:

{  "a": 1,

  "b": 2

}

4. Reading the JSON File

with open('data.json', 'r') as file:

    print(json.load(file).get('b', 0))

open('data.json', 'r'):

Opens the file in read mode ('r').

json.load(file):

Reads the JSON data from the file and converts it back into a Python dictionary.

.get('b', 0):

The .get() method fetches the value associated with the key 'b'.

If 'b' is not found, it would return the default value 0, but in this case 'b' exists.

Output Explanation

The key 'b' exists in the dictionary with the value 2.

Therefore, the print() statement will output:

2

Final Output:

2

Sunday, 30 March 2025

Python Coding challenge - Day 420| What is the output of the following Python Code?









Code Explanation:

1. Importing the NumPy Library

import numpy as np

NumPy is a fundamental Python library for numerical computations.

It provides functions for working with arrays, matrices, linear algebra, and more.

The alias np is a common convention for importing NumPy.

2. Creating a Matrix Using NumPy

matrix = np.array([

    [4, 2],

    [1, 3]])

np.array() is used to create a NumPy array representing a matrix.

The matrix is a 2x2 square matrix with 2 rows and 2 columns.

3. Understanding Eigenvalues and Eigenvectors

Eigenvalues and Eigenvectors are fundamental concepts in linear algebra.

For a square matrix ๐ด

A, if there exists a scalar ๐œ†

ฮป and a non-zero vector ๐‘ฃ

v such that:๐ด⋅๐‘ฃ=๐œ†⋅๐‘ฃ

Then:

ฮป is called an eigenvalue

v is called the corresponding eigenvector.

Finding Eigenvalues Using NumPy

eigenvalues, eigenvectors = np.linalg.eig(matrix)

np.linalg.eig() is a NumPy function used to calculate eigenvalues and eigenvectors of a square matrix.

It returns:

eigenvalues: A NumPy array of the eigenvalues.

eigenvectors: A matrix where each column represents an eigenvector.

4. Rounding the Eigenvalues

print(np.round(eigenvalues, 2))

np.round() is used to round the eigenvalues to two decimal places for clearer output.

It makes results more readable and is especially useful for complex numbers.

5. Calculation of Eigenvalues (Manual Method)

The characteristic polynomial of matrix ๐ด

A is:det(A−ฮปI)=0 

Final Output

[5. 2.]



Python Coding challenge - Day 419| What is the output of the following Python Code?

 


Code Explanation: 

1. Importing the NumPy Library

import numpy as np

numpy is a powerful Python library for numerical computations.

It provides functions for working with arrays, matrices, and mathematical operations.

np is the commonly used alias for numpy.

2. Creating a Matrix Using NumPy

matrix = np.array([[3, 5, 1], 

                    [4, 6, 2], 

                    [7, 8, 9]])

np.array() is used to create a NumPy array (a matrix in this case).

The matrix is a 3x3 square matrix with three rows and three columns.

 3. Understanding Matrix Trace

The trace of a square matrix is the sum of its diagonal elements.

The diagonal elements are the ones where the row index equals the column index (from top-left to bottom-right).

4. Calculating the Trace Using NumPy

trace_value = np.trace(matrix)

np.trace() is a built-in NumPy function that directly calculates the trace of a square matrix.

It efficiently sums the diagonal elements.

5. Printing the Result

print("Trace:", trace_value)

This prints the calculated trace value.

The output will be:

Trace: 18

Arc Twirl Pattern using Python

 


import numpy as np

import matplotlib.pyplot as plt

theta = np.linspace(0, 6 * np.pi, 1000)

r = 1 + 0.2 * np.sin(5 * theta)

x = r * np.cos(theta)

y = r * np.sin(theta)

plt.figure(figsize=(7, 7))

plt.plot(x, y, color='teal', linewidth=2)

for i in range(1, 6):

    arc_theta = np.linspace(0, 2 * np.pi / i, 300)

    arc_r = 0.8 + 0.1 * i

    arc_x = arc_r * np.cos(arc_theta)

    arc_y = arc_r * np.sin(arc_theta)

    plt.plot(arc_x, arc_y, color='darkcyan', linewidth=1.5, alpha=0.6)

plt.gca().set_aspect('equal')

plt.axis('off')

plt.title('Arc Twirl Pattern')

plt.show()

#source code --> clcoding.com 


Code Explanation:

1. Import Libraries

import numpy as np

import matplotlib.pyplot as plt

numpy: Used for numerical operations like generating a range of values for the angles and radii.

matplotlib.pyplot: Used for plotting and visualizing the pattern.

2. Define Parameters for the Arc Twirl Effect

theta = np.linspace(0, 6 * np.pi, 1000)

r = 1 + 0.2 * np.sin(5 * theta)

theta: Creates a range of 1000 values between 0 and 6 * np.pi (approximately 18.85). This is the angle parameter used to generate the spiral.

r: The radius at each angle theta is calculated. The formula 1 + 0.2 * np.sin(5 * theta) introduces oscillations to the radius as theta increases, which creates a twirling effect.

3. Convert Polar Coordinates to Cartesian Coordinates

x = r * np.cos(theta)

y = r * np.sin(theta)

x and y: Convert the polar coordinates (r, theta) into Cartesian coordinates (x, y) using the formulas:

x = r * cos(theta)

y = r * sin(theta)

These are the coordinates needed to plot the spiral pattern on a 2D graph.

4. Create the Plot

plt.figure(figsize=(7, 7))

plt.plot(x, y, color='teal', linewidth=2)

plt.figure(figsize=(7, 7)): Creates a new figure with a square aspect ratio of 7x7 inches.

plt.plot(x, y, color='teal', linewidth=2): Plots the spiral defined by the x and y values with a teal color and a line width of 2. This creates the main spiral pattern.

5. Adding Arcs with Variation

for i in range(1, 6):

    arc_theta = np.linspace(0, 2 * np.pi / i, 300)

    arc_r = 0.8 + 0.1 * i

    arc_x = arc_r * np.cos(arc_theta)

    arc_y = arc_r * np.sin(arc_theta)

    plt.plot(arc_x, arc_y, color='darkcyan', linewidth=1.5, alpha=0.6)

for i in range(1, 6): A loop that generates 5 additional arc patterns, each with a different radius and number of points.

arc_theta: For each arc, arc_theta is a range of angles from 0 to 2 * np.pi / i with 300 points, which defines how much of a full circle the arc will cover.

arc_r: The radius for each arc starts at 0.8 and increases by 0.1 * i in each iteration. This creates expanding arcs with each loop iteration.

arc_x and arc_y: These calculate the x and y Cartesian coordinates for the arcs.

plt.plot(arc_x, arc_y, color='darkcyan', linewidth=1.5, alpha=0.6): Plots the arcs using a darkcyan color, with a line width of 1.5 and transparency (alpha=0.6) to give them a subtle appearance, allowing the main spiral to remain prominent.

6. Styling

plt.gca().set_aspect('equal')

plt.axis('off')

plt.title("Arc Twirl", fontsize=20, color='teal')

plt.gca().set_aspect('equal'): Sets the aspect ratio to "equal," meaning the units on the x and y axes are scaled equally. This ensures that the arcs and spiral remain circular rather than stretched.

plt.axis('off'): Turns off the axis lines and labels for a clean look.

plt.title("Arc Twirl", fontsize=20, color='teal'): Adds a title to the plot "Arc Twirl" in a teal color with a font size of 20.

7. Display the Plot

plt.show()

plt.show(): Displays the final plot with all the arcs and spiral patterns.


Python Coding Challange - Question With Answer(01300325)

 


Understanding any() Function:

  • The any() function checks if at least one element in the iterable satisfies the given condition.

  • The condition used is num % 5 == 0, which checks if the number is divisible by 5.

Step-by-Step Execution:

First List: numbers1 = [10, 20, 33]

  • 10 % 5 == 0 ✅ (True)

  • 20 % 5 == 0 ✅ (True)

  • 33 % 5 == 0 ❌ (False)

Since at least one number (10 and 20) is divisible by 5, any() returns True.

Second List: numbers2 = [7, 15, 27]

  • 7 % 5 == 0 ❌ (False)

  • 15 % 5 == 0 ✅ (True)

  • 27 % 5 == 0 ❌ (False)

Since 15 is divisible by 5, any() returns True.

Third List: numbers3 = [9, 14, 21]

  • 9 % 5 == 0 ❌ (False)

  • 14 % 5 == 0 ❌ (False)

  • 21 % 5 == 0 ❌ (False)

Since no number in the list is divisible by 5, any() returns False.

Final Output:


True
True
False

CHECK NOW 400 Days Python Coding Challenges with Explanation

https://pythonclcoding.gumroad.com/l/sputu

Friday, 28 March 2025

Python Coding Challange - Question With Answer(01280325)

 


Explaining String Slicing: word[4:-3:2] in Python

Given the string:


word = 'pythonCoding'

Let's break down the slicing operation [4:-3:2]:

Understanding the Slicing Syntax


word[start:end:step]
  • start = 4 → Begins at index 4 (5th character).

  • end = -3 → Stops at index -3 (3rd character from the end, not included).

  • step = 2 → Selects every second character.


Indexing the String


word = 'pythonCoding'
p y t h o n C o d i n g index 0 1 2 3 4 5 6 7 8 9 10 11
-index -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

Now, applying word[4:-3:2]:

  1. Start at index 4 → 'o'

  2. Step by 2:

    • Index 6 → 'C'

    • Index 8 → 'd'

  3. Stop before index -3 ('i')

Thus, the selected characters are 'oCd'.


Verifying with Code


word = 'pythonCoding'
print(word[4:-3:2]) # Output: 'oCd'

Visualizing the Selection


word = 'pythonCoding'
p y t h o n C o d i n g index 0 1 2 3 4 5 6 7 8 9 10 11 ↓ ↓ ↓
o C d

Each selected character:

  • 'o' → (index 4)

  • 'C' → (index 6, after skipping n)

  • 'd' → (index 8, after skipping o)

The slicing stops before reaching 'i' (index -3).


Conclusion

This slicing technique efficiently extracts a pattern of characters using:  Sart and end indexes
Step size for skipping characters
Combination of positive & negative indexing


Check Now 100 Python Programs for Beginner with explanation

https://pythonclcoding.gumroad.com/l/qijrws

Cycloid and Epicycloid Pattern using Python

 


import numpy as np

import matplotlib.pyplot as plt

r = 1

theta = np.linspace(0, 4 * np.pi, 1000)

x_cycloid = r * (theta - np.sin(theta))

y_cycloid = r * (1 - np.cos(theta))

R = 3

r_epicycloid = 1

x_epicycloid = (R + r_epicycloid) * np.cos(theta) - r_epicycloid * np.cos((R + r_epicycloid) / r_epicycloid * theta)

y_epicycloid = (R + r_epicycloid) * np.sin(theta) - r_epicycloid * np.sin((R + r_epicycloid) / r_epicycloid * theta)

plt.figure(figsize=(10, 5))

plt.subplot(1, 2, 1)

plt.plot(x_cycloid, y_cycloid, color='blue')

plt.title('Cycloid')

plt.axis('equal')

plt.subplot(1, 2, 2)

plt.plot(x_epicycloid, y_epicycloid, color='red')

plt.title('Epicycloid')

plt.axis('equal')

plt.tight_layout()

plt.show()

#source code --> clcoding.com 

Code Explanation:

1. Importing Libraries
import numpy as np
import matplotlib.pyplot as plt
NumPy: Used for creating numerical arrays and performing mathematical operations.
Matplotlib: Used for plotting the Cycloid and Epicycloid curves.

2. Define Parameters for the Cycloid
r = 1
theta = np.linspace(0, 4 * np.pi, 1000)
r = 1: Radius of the generating circle.
theta: Array of 1000 values equally spaced from 0 to 4ฯ€, representing the angle in radians.
This ensures a smooth plot for one complete oscillation.

3. Calculate the Cycloid Coordinates
x_cycloid = r * (theta - np.sin(theta))
y_cycloid = r * (1 - np.cos(theta))
Cycloid Equation:
x=r(t−sin(t)),y=r(1−cos(t))
Explanation:
x represents the horizontal motion of a point on the wheel as it rolls.
y represents the vertical motion of the point.

This forms a Cycloid — the path traced by a point on a rolling circle.

4. Define Parameters for the Epicycloid
R = 3
r_epicycloid = 1
R = 3: Radius of the stationary larger circle.
r_epicycloid = 1: Radius of the smaller rotating circle that rolls on the outside.

5. Calculate the Epicycloid Coordinates
x_epicycloid = (R + r_epicycloid) * np.cos(theta) - r_epicycloid * np.cos((R + r_epicycloid) / r_epicycloid * theta)
y_epicycloid = (R + r_epicycloid) * np.sin(theta) - r_epicycloid * np.sin((R + r_epicycloid) / r_epicycloid * theta)

Epicycloid Equation:
Explanation:
R is the radius of the fixed circle.
r is the radius of the rolling circle.
The trace of a point on the smaller circle as it rolls on the outer edge of the larger circle forms an Epicycloid.

6. Plot the Cycloid and Epicycloid
plt.figure(figsize=(10, 5))
Creates a figure of size 10x5 for side-by-side comparison.

7. Plot Cycloid
plt.subplot(1, 2, 1)
plt.plot(x_cycloid, y_cycloid, color='blue')
plt.title('Cycloid')
plt.axis('equal')
plt.subplot(1, 2, 1) creates the left plot (Cycloid).

plt.plot() plots the blue Cycloid.

plt.axis('equal') ensures the aspect ratio is equal, so the curve is accurately represented.

8. Plot Epicycloid
plt.subplot(1, 2, 2)
plt.plot(x_epicycloid, y_epicycloid, color='red')
plt.title('Epicycloid')
plt.axis('equal')
plt.subplot(1, 2, 2) creates the right plot (Epicycloid).

plt.plot() plots the red Epicycloid.

9. Final Touch and Display
plt.tight_layout()
plt.show()
plt.tight_layout() adjusts subplot spacing to prevent overlapping.
plt.show() renders the plot on the screen.


Pendulum Wave Art Pattern using Python

import numpy as np

import matplotlib.pyplot as plt

import matplotlib.animation as animation

num_pendulums = 15

lengths = np.linspace(1, 2, num_pendulums)

g = 9.81  

time = np.linspace(0, 20, 1000)

periods = 2 * np.pi * np.sqrt(lengths / g)

angles = [np.cos(2 * np.pi * time / T) for T in periods]

x_pos = [l * np.sin(angle) for l, angle in zip(lengths, angles)]

y_pos = [-l * np.cos(angle) for l, angle in zip(lengths, angles)]

fig, ax = plt.subplots(figsize=(8, 8))

ax.set_xlim(-2.5, 2.5)

ax.set_ylim(-2.5, 0.5)

ax.set_aspect('equal')

ax.set_title('Pendulum Wave Art Plot')

lines = [ax.plot([], [], 'o-', markersize=10)[0] for _ in range(num_pendulums)]

def animate(i):

    for j, line in enumerate(lines):

        line.set_data([0, x_pos[j][i]], [0, y_pos[j][i]])

    return lines

ani = animation.FuncAnimation(fig, animate, frames=len(time), interval=30, blit=True)

plt.show()

#source code --> clcoding.com 

Code Explanation:

1. Importing Libraries
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
NumPy: For efficient mathematical operations.
Matplotlib: For plotting and visualizing.
Matplotlib Animation: For creating the pendulum wave animation.

2. Initialization
num_pendulums = 15
lengths = np.linspace(1, 2, num_pendulums)
g = 9.81
time = np.linspace(0, 20, 1000)
num_pendulums: Number of pendulums in the animation (15 in this case).
lengths: Linearly spaced pendulum lengths from 1 to 2 meters using np.linspace.
g: Gravitational acceleration (9.81 m/s²).
time: Array representing 1000 time steps from 0 to 20 seconds.

3. Calculating Pendulum Motion
periods = 2 * np.pi * np.sqrt(lengths / g)
Formula Used: The period of a simple pendulum is given by:
T=2ฯ€ root l/g
T = Period of oscillation
L = Length of the pendulum
g = Gravitational acceleration

4. Calculating Angular Position (ฮธ)
angles = [np.cos(2 * np.pi * time / T) for T in periods]
Using the equation:
ฮธ(t)=cos(2ฯ€t/T)
The angles are calculated for each pendulum over time using cosine function for oscillatory motion.

5. Converting to Cartesian Coordinates
x_pos = [l * np.sin(angle) for l, angle in zip(lengths, angles)]
y_pos = [-l * np.cos(angle) for l, angle in zip(lengths, angles)]
The x and y positions of the pendulum are calculated using trigonometry:
x=Lsin(ฮธ)
y=−Lcos(ฮธ)
The negative y ensures the pendulum moves downwards.

6. Plot Setup
fig, ax = plt.subplots(figsize=(8, 8))
ax.set_xlim(-2.5, 2.5)
ax.set_ylim(-2.5, 0.5)
ax.set_aspect('equal')
ax.set_title('Pendulum Wave Art Plot')
A figure of size 8x8 is created.
x and y limits are adjusted to fit all pendulums.
ax.set_aspect('equal') ensures equal scaling on both axes.
A title is added.

7. Creating the Pendulums
lines = [ax.plot([], [], 'o-', markersize=10)[0] for _ in range(num_pendulums)]
The pendulums are visualized using markers ('o-') with a size of 10.
Each pendulum is represented as a line starting from the origin (0, 0).

8. Animation Function
def animate(i):
    for j, line in enumerate(lines):
        line.set_data([0, x_pos[j][i]], [0, y_pos[j][i]])
    return lines
animate() updates the pendulum positions for each frame (i).

set_data() updates the line data to simulate the swinging motion.

9. Creating and Displaying Animation
ani = animation.FuncAnimation(fig, animate, frames=len(time), interval=30, blit=True)
plt.show()
FuncAnimation: Handles the animation by repeatedly calling the animate() function.

interval=30 means each frame is displayed for 30 milliseconds.

blit=True optimizes the rendering for smoother animations.

 

Thursday, 27 March 2025

Mountain Horizon Pattern using Python

 


import numpy as np

import matplotlib.pyplot as plt

num_layers = 7

x = np.linspace(0, 10, 500)

plt.figure(figsize=(8, 6))

for i in range(num_layers):

    y = 1.5 * np.sin(x + i * 0.5) + np.random.uniform(-0.2, 0.2, size=x.shape) + (i * 0.8)

    color = (0.2, 0.3, 0.5, 1 - i / (num_layers + 1))

    plt.fill_between(x, y, -5, color=color)

plt.axis('off')

plt.gca().set_aspect('auto', adjustable='box')

plt.title('Mountain Horizon Pattern', fontsize=14)

plt.show()

#source code --> clcoding.com

Code Explanation:

1. Importing Libraries

import numpy as np

import matplotlib.pyplot as plt

NumPy: Used for mathematical operations and to generate smooth x-values (np.linspace) and random noise (np.random.uniform).

Matplotlib: Used to plot and visualize the mountains using plt.fill_between().

 2. Parameters and Initialization

num_layers = 7

x = np.linspace(0, 10, 500)

plt.figure(figsize=(10, 6))

num_layers = 7: The number of mountain layers to be drawn, creating a sense of depth.

x = np.linspace(0, 10, 500):

Generates 500 points between 0 and 10 for the x-axis, ensuring smooth curves.

plt.figure(figsize=(10, 6)):

Creates a figure with a size of 10x6 inches, providing a wide, scenic view.

 3. Creating the Mountain Layers

for i in range(num_layers):

    y = 1.5 * np.sin(x + i * 0.5) + np.random.uniform(-0.2, 0.2, size=x.shape) + (i * 0.8)

for i in range(num_layers): A loop that generates each layer of mountains.

np.sin(x + i * 0.5):

A sine wave creates the smooth, wavy shape of the mountains.

The i * 0.5 adds a phase shift to differentiate the layers.

np.random.uniform(-0.2, 0.2, size=x.shape):

Adds small random variations (noise) to the wave, making the mountains look more natural and rugged.

(i * 0.8):

Gradually raises each subsequent layer, simulating mountains in the distance.

 4. Adding Color with Transparency

color = (0.2, 0.3, 0.5, 1 - i / (num_layers + 1))

Color: Uses an RGBA value where:

 Red (0.2), Green (0.3), and Blue (0.5) create a cool blue tone, like distant mountains.

Alpha (1 - i / (num_layers + 1)) controls transparency.

Closer mountains are darker and more opaque.

Distant mountains are lighter and more transparent, creating an atmospheric perspective.

 5. Plotting the Mountains

plt.fill_between(x, y, -5, color=color)

plt.fill_between():

Fills the area between the mountain curve (y) and the bottom of the plot (-5).

This creates the solid mountain silhouette.

 6. Adjusting the Plot

plt.axis('off')

plt.gca().set_aspect('auto', adjustable='box')

plt.title('Mountain Horizon Pattern', fontsize=14)

plt.show()

plt.axis('off'): Hides the axis for a clean, artistic look.

plt.gca().set_aspect('auto', adjustable='box'):

Ensures the aspect ratio adjusts naturally to fit the plot.

plt.title(): Adds a descriptive title.

plt.show(): Displays the final output.


Popular Posts

Categories

100 Python Programs for Beginner (118) AI (150) Android (25) AngularJS (1) Api (6) Assembly Language (2) aws (27) Azure (8) BI (10) Books (251) Bootcamp (1) C (78) C# (12) C++ (83) Course (84) Coursera (298) Cybersecurity (28) Data Analysis (24) Data Analytics (16) data management (15) Data Science (216) Data Strucures (13) Deep Learning (67) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (17) Finance (9) flask (3) flutter (1) FPL (17) Generative AI (47) Git (6) Google (47) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (41) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (185) Meta (24) MICHIGAN (5) microsoft (9) Nvidia (8) Pandas (11) PHP (20) Projects (32) Python (1215) Python Coding Challenge (882) Python Quiz (341) Python Tips (5) Questions (2) R (72) React (7) Scripting (3) security (4) Selenium Webdriver (4) Software (19) SQL (45) Udemy (17) UX Research (1) web application (11) Web development (7) web scraping (3)

Followers

Python Coding for Kids ( Free Demo for Everyone)