Sunday, 20 April 2025

3D Topographical Pattern using Python

 


import matplotlib.pyplot as plt

import numpy as np

from mpl_toolkits.mplot3d import Axes3D

x=np.linspace(-5,5,100)

y=np.linspace(-5,5,100)

x,y=np.meshgrid(x,y)

z=np.sin(np.sqrt(x**2+y**2))

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

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

surface=ax.plot_surface(x,y,z,cmap='terrain',edgecolor='none')

fig.colorbar(surface)

ax.set_xlabel('X (Longitude)')

ax.set_ylabel('Y(Latitude)')

ax.set_zlabel('Z(Elevation)')

ax.set_title('3D Topographical pattern')

plt.show()

#source code --> clcoding.com 

Code Explanation:

1. Importing Libraries

import numpy as np

import matplotlib.pyplot as plt

from mpl_toolkits.mplot3d import Axes3D

numpy (np): Used for numerical operations like creating arrays and applying mathematical functions.

 matplotlib.pyplot (plt): Used for plotting graphs and figures.

 mpl_toolkits.mplot3d: Adds support for 3D plotting using Axes3D.

 2. Creating Grid Data

x = np.linspace(-5, 5, 100)

y = np.linspace(-5, 5, 100)

x, y = np.meshgrid(x, y)

np.linspace(-5, 5, 100): Creates 100 evenly spaced points from -5 to 5 for both x and y axes.

 np.meshgrid(x, y): Creates a 2D grid of all combinations of x and y — needed for surface plotting.

 3. Defining the Elevation (Z-values)

z = np.sin(np.sqrt(x**2 + y**2))

This creates elevation data using a sine wave based on the distance from the origin (0,0). It looks like ripples or waves radiating from the center.

 Formula breakdown:

x**2 + y**2: Computes the square of the distance.

np.sqrt(...): Takes the square root → gives radial distance.

np.sin(...): Applies the sine function to generate oscillations.

 4. Creating the Plot Figure

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

Initializes a new figure window.

figsize=(10, 7): Sets the width and height of the figure in inches.

 5. Adding a 3D Subplot

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

Adds a 3D plotting area to the figure.

111 = 1 row, 1 column, 1st subplot.

projection='3d': Tells matplotlib to enable 3D plotting for this subplot.

 6. Plotting the 3D Surface

surface = ax.plot_surface(x, y, z, cmap='terrain', edgecolor='none')

Creates the 3D surface from x, y, and z data.

cmap='terrain': Applies a terrain color map to simulate real-world elevation colors (greens, browns, etc.).

edgecolor='none': Removes grid lines for a cleaner look.

 7. Adding a Color Bar

fig.colorbar(surface)

Adds a color bar beside the plot.

Shows how colors map to elevation values (Z-axis).

 8. Labeling the Axes

ax.set_xlabel('X (Longitude)')

ax.set_ylabel('Y (Latitude)')

ax.set_zlabel('Z (Elevation)')

Labels each axis for clarity:

 X: "Longitude"

Y: "Latitude"

Z: "Elevation"

 9. Setting the Plot Title

ax.set_title('3D Topographical Plot')

Adds a descriptive title to the top of the plot.

 10. Displaying the Plot

plt.show()

Renders the plot in a window or notebook.

Allows for interactive rotation, zoom, and pan if run in a GUI or Jupyter Notebook.

 


Torus Knot Pattern using Python

 


import matplotlib.pyplot as plt

import numpy as np

from mpl_toolkits.mplot3d import Axes3D

R=3

r=1

p=2

q=3

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

x=(R+r*np.cos(q*theta))*np.cos(p*theta)

y=(R+r*np.cos(q*theta))*np.sin(p*theta)

z=r*np.sin(q*theta)

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

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

ax.plot(x,y,z,color='purple',lw=2)

ax.set_xlabel('X Axis')

ax.set_ylabel('Y Axis')

ax.set_zlabel('Z Axis')

ax.set_title('Torus Knot',fontsize=16)

plt.show()

#source code --> clcoding.com

Code Explanation:

Imports:

import numpy as np

import matplotlib.pyplot as plt

from mpl_toolkits.mplot3d import Axes3D

numpy: Used for numerical calculations and to generate the array of angles (theta) for the parametric equations.

 matplotlib.pyplot: Used to plot the 3D torus knot.

 mpl_toolkits.mplot3d: Provides the necessary tools to create 3D plots in matplotlib.

 Parameters:

R = 3

r = 1

p = 2 

q = 3

R: The radius of the central circle of the torus. This determines the distance from the center of the hole to the center of the tube (doughnut shape).

 r: The radius of the tube itself. This controls the thickness of the torus.

 p and q: These are the parameters that determine how many times the knot will wind around the tube and the hole of the torus.

 p: The number of times the knot winds around the tube of the torus.

 q: The number of times the knot winds around the central hole of the torus.

 In this case, the values are set as:

 p = 2: The knot will loop around the tube 2 times.

 q = 3: The knot will loop around the hole 3 times.

 Parameter Array (theta):

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

theta is the angle parameter that will range from 0 to 2ฯ€, which represents one full rotation around the circle.

 The np.linspace(0, 2 * np.pi, 1000) generates 1000 evenly spaced values between 0 and 2ฯ€, which will be used to plot the curve.

 Parametric Equations for the Torus Knot:

x = (R + r * np.cos(q * theta)) * np.cos(p * theta)

y = (R + r * np.cos(q * theta)) * np.sin(p * theta)

z = r * np.sin(q * theta)

The 3D coordinates (x, y, z) are computed using parametric equations. These equations define the position of each point on the knot:

 X-coordinate (x):

x(ฮธ)=(R+rcos(qฮธ))cos(pฮธ)

This equation describes the horizontal position of the point as it winds around the torus.

 Y-coordinate (y):

y(ฮธ)=(R+rcos(qฮธ))sin(pฮธ)

This equation describes the vertical position of the point, complementing the X-coordinate to form the loop around the torus.

Z-coordinate (z):

z(ฮธ)=rsin(qฮธ)

This equation determines the height of the point relative to the horizontal plane. It ensures the knot's winding around the hole of the torus.

 Plotting the Torus Knot:

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

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

 ax.plot(x, y, z, color='purple', lw=2)

ax.set_title(f'Torus Knot (p={p}, q={q})', fontsize=16)

ax.set_xlabel('X axis')

ax.set_ylabel('Y axis')

ax.set_zlabel('Z axis')

plt.show()

 Creating the Figure:

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

Creates a figure of size 8x8 inches to hold the plot.

 Creating a 3D Axes Object:

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

Adds a 3D subplot to the figure. The projection='3d' argument specifies that the axes should be 3-dimensional.

 Plotting the Knot:

ax.plot(x, y, z, color='purple', lw=2)

Plots the points (x, y, z) on the 3D axes. The curve is colored purple, and the line width is set to 2.

 Setting Labels and Title:

ax.set_title(f'Torus Knot (p={p}, q={q})', fontsize=16)

ax.set_xlabel('X axis')

ax.set_ylabel('Y axis')

ax.set_zlabel('Z axis')

ax.set_title(): Sets the title of the plot, which includes the values of p and q to indicate which specific torus knot is being displayed.

 ax.set_xlabel(), ax.set_ylabel(), ax.set_zlabel(): Labels the X, Y, and Z axes respectively.

 Displaying the Plot:

plt.show()

Displays the plot in a new window.


Friday, 18 April 2025

Python Coding Challange - Question with Answer (01180425)

 


Let's break down this Python for loop:

for i in range(0, -2, -2):
print(i)

range(start, stop, step) parameters:

  • start = 0 → where the sequence starts

  • stop = -2 → where the sequence stops (but this value is not included)

  • step = -2 → step (going down by 2)

What happens here?

This range(0, -2, -2) generates a sequence starting at 0 and moves backward in steps of -2, stopping before -2.

So it produces:

[0]

Because:

  • 0 is included ✔️

  • Next value would be -2, but the range excludes the stop value, so it's not included ❌

Output:

0

Summary:

This loop runs only once, printing 0.

APPLICATION OF PYTHON FOR CYBERSECURITY

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

Thursday, 17 April 2025

Python Coding Challange - Question with Answer (01170425)

 


Let me explain this code:


num = 1

while num < 6:

    print(num)

This code has a few issues that would cause it to run indefinitely (infinite loop). Let me break down why and how to fix it:


First, num = 1 initializes a variable num with the value 1

The while loop continues executing as long as num < 6 is True

Inside the loop, print(num) prints the current value of num

However, the code is missing an increment statement to update num, so num will always stay 1 and the condition num < 6 will always be True

Here's the corrected version:


python    num += 1  # Increment num by 1 in each iteration

num += 1  # Increment num by 1 in each iteration


This corrected version will:

1. Start with num = 1

2. Print: 1

3. Increment num to 2

4. Print: 2

5. Increment num to 3

6. Print: 3

7. Increment num to 4

8. Print: 4

9. Increment num to 5

10. Print: 5

11. Increment num to 6

12. Stop (because num < 6 is no longer True)


The output will be:

1

2

3

4

5



The key lesson here is that when using while loops, you need to make sure:

1. You have a proper condition that will eventually become False

2. You update the variables involved in the condition inside the loop

3. The loop has a clear way to terminate

400 Days Python Coding Challenges with Explanation

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



Wednesday, 16 April 2025

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

 


Code Explanation:

1. Import Necessary Libraries
from sklearn.tree import DecisionTreeClassifier
import numpy as np
DecisionTreeClassifier: This is an implementation of a decision tree algorithm used for classification tasks. It learns from labeled data (X, y) and can make predictions based on the learned rules.
numpy: numpy is used to handle arrays, which are commonly used for data manipulation and storage. Here, it's used to create the input data X and target labels y.

2. Define Input Data and Labels
X, y = np.array([[1, 2], [2, 3]]), np.array([0, 1])
X: This is the input feature matrix, where each row represents a sample and each column represents a feature. In this case, X is a 2x2 matrix:
X = [[1, 2],
     [2, 3]]
The first sample is [1, 2], and the second sample is [2, 3].
y: This is the target label array, where each element corresponds to the label of the respective sample in X. Here:
y = [0, 1]
The first sample ([1, 2]) has a label 0, and the second sample ([2, 3]) has a label 1.

3. Train the Decision Tree Classifier
clf = DecisionTreeClassifier().fit(X, y)
DecisionTreeClassifier(): This initializes a decision tree classifier object.

.fit(X, y): This method fits the decision tree model to the data X (input features) and y (target labels). During fitting, the decision tree algorithm learns the relationship between the features in X and the corresponding labels in y.
In this case, the decision tree will try to learn how to classify based on the two features. The decision tree algorithm works by recursively splitting the feature space into subsets based on feature values that provide the best separation between the classes (minimizing impurity like Gini impurity or entropy).

For such a small dataset, the decision tree will create a simple rule to separate the two samples based on their features:
It will notice that the first sample ([1, 2]) is labeled 0 and the second sample ([2, 3]) is labeled 1.
The tree will effectively create a rule to classify these two points correctly.

4. Make a Prediction
print(clf.predict([[2, 3]]))
clf.predict([[2, 3]]): This method is used to predict the class label for the input [[2, 3]]. This input is a new sample with features [2, 3], which is exactly the same as the second sample in the training data.
The model already knows that the second sample [2, 3] corresponds to the class 1 (from the training data). So, the decision tree will predict that the label for the input [2, 3] is 1.

The output of the code will be:


[1]

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

 


Code Explanation:

1. Import TensorFlow

import tensorflow as tf

This imports the TensorFlow library, which is widely used for machine learning and deep learning tasks. Here, we will use it to calculate the gradient of a function with respect to a variable.

2. Create a TensorFlow Variable

x = tf.Variable(4.0)

tf.Variable(4.0) creates a TensorFlow variable with an initial value of 4.0. Variables in TensorFlow are used to store and update the model's parameters during training.

The value 4.0 is stored in the variable x, and TensorFlow will track its value and compute gradients with respect to it.

3. Gradient Tape Context

with tf.GradientTape() as tape:

    y = x**3 + 2*x + 1

tf.GradientTape() is used to record operations for automatic differentiation (i.e., computing gradients).

Inside the with block, the expression y = x**3 + 2*x + 1 computes the function y in terms of x. TensorFlow will track the operations performed on x so it can later compute the gradient with respect to x.

The expression y = x**3 + 2*x + 1 is a polynomial function of x. 

4. Calculate the Gradient

grad = tape.gradient(y, x)

tape.gradient(y, x) computes the gradient of y with respect to x. This means that TensorFlow will take the derivative of the function y = x^3 + 2x + 1 with respect to x and return the result.

5. Print the Gradient

print(grad)

This will print the computed gradient of the function. In this case, it will output 50.0, which is the result of the derivative evaluated at x = 4.0.

Final Output:

50

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

 


Step-by-step Explanation:

Initialize an empty list funcs:

funcs = []

This is just creating an empty list, where functions will be stored.

Loop over the range 3:

for i in range(3):

The for loop runs three times, with i taking values 0, 1, and 2 in each iteration.

Define the function f() inside the loop:

def f(): return i

A function f() is defined within the loop that returns the value of i when called.

At this point, the function f is being defined, but it doesn't immediately execute. The definition of f happens in the current scope of the loop, which means that f will "remember" the variable i when it is called, but it does not capture the value of i at the time the function was defined (which is crucial to understanding the behavior).

Append the function f() to funcs list:

funcs.append(f)

The function f (which is defined within the loop) is added to the funcs list. However, because of the late binding behavior in Python, the function f does not capture the value of i at the moment it is defined. Instead, it captures the reference to i, meaning it always uses the current value of i when it is called.

This behavior will be important later: after the loop finishes, all functions in funcs will reference the final value of i, which is 2 (since the loop ends when i = 2).

Calling each function in the funcs list:

print([fn() for fn in funcs])

This line creates a list comprehension that calls each function (fn()) stored in the funcs list and prints the result. Let’s analyze what happens when each function is called:

When calling any function in funcs, the value of i is not the value i at the time the function was added to the list; instead, it is the final value of i after the loop ends.

Since the loop finishes with i = 2, all functions in funcs will return the value 2.

Therefore, when each of the functions in funcs is called, they all return 2.

Output:

[2, 2, 2]

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

 



Code Explanation:

1. Importing lru_cache from functools

from functools import lru_cache

lru_cache is a decorator provided by the functools module. It stands for "Least Recently Used Cache." The decorator caches the results of function calls so that subsequent calls with the same arguments can return the cached result, rather than recomputing it.

Why use lru_cache?

Memoization is an optimization technique to improve performance by storing the results of expensive function calls and reusing them when the same inputs occur again. This avoids redundant computations in recursive functions, which is especially useful in problems that involve overlapping subproblems, like the Fibonacci sequence.

2. The Function f(x)

@lru_cache()

def f(x):

    if x < 3: 

        return x

    return f(x - 1) + f(x - 2)

@lru_cache(): This decorator applies caching to the f(x) function. It stores previously computed values of f(x) so that if f(x) is called again with the same x, the function doesn't need to recompute the result.

Base Case (if x < 3):

The function returns x directly when x is less than 3. This is the base case of the recursion. For x = 0, 1, 2, the function just returns x.

Recursive Case:

For x >= 3, the function calls itself recursively:

return f(x - 1) + f(x - 2)

This means that f(x) is the sum of the previous two values: f(x - 1) and f(x - 2).

This recursive structure is similar to the Fibonacci sequence, where each term is the sum of the previous two terms.

3. Calling f(5)

print(f(5))

Now, let's walk through the computation of f(5) step-by-step:

f(5):f(5) calls f(4) and f(3).

f(4):f(4) calls f(3) and f(2).

f(3):f(3) calls f(2) and f(1).

Base Cases:

f(2) and f(1) return 2 and 1, respectively (as per the base case).

Now we have:

f(2) returns 2.

f(1) returns 1.

f(3) becomes f(2) + f(1) = 2 + 1 = 3.

Continuing to f(4):

Now, we can compute f(4):

f(4) calls f(3) and f(2).

f(3) is already computed as 3 (due to caching from the earlier calculation).

f(2) is also cached as 2.

Therefore, f(4) = f(3) + f(2) = 3 + 2 = 5.

Finally, computing f(5):

Now we can compute f(5):

f(5) calls f(4) and f(3).

f(4) is already cached as 5.

f(3) is already cached as 3.

Therefore, f(5) = f(4) + f(3) = 5 + 3 = 8.

4. Memoization and Caching

The memoization (enabled by @lru_cache()) ensures that intermediate results like f(4), f(3), f(2), and f(1) are computed only once. After the first computation of each value, the results are stored in the cache, and subsequent calls with the same argument will simply return the cached result, making the function much faster.

For example, when computing f(5), f(3) is computed only once, and its result is reused when computing f(4) and f(5).

5. Output

print(f(5))

Finally, f(5) evaluates to 8, so the output of the program will be:

8

3D Parametric Helix Pattern using Python

 


import matplotlib.pyplot as plt

import numpy as np

from mpl_toolkits.mplot3d import Axes3D

n=1000

t=np.linspace(0,10*np.pi,n)

x=np.sin(t)

y=np.cos(t)

z=t

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

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

ax.plot(x,y,z,color='purple',lw=2)

ax.set_title("3D Parametric Helix Pattern",fontsize=16)

ax.set_xlabel('X axis')

ax.set_xlabel('Y axis')

ax.set_xlabel('Z axis')

plt.show()

#source code --> clcoding.com

Code Explanation:

1. Import Libraries

 import numpy as np

import matplotlib.pyplot as plt

from mpl_toolkits.mplot3d import Axes3D

import numpy as np: Imports the numpy library, which is used for numerical calculations, such as generating the spiral coordinates.

import matplotlib.pyplot as plt: Imports matplotlib, which is used for plotting 2D and 3D graphs.

from mpl_toolkits.mplot3d import Axes3D: Imports the Axes3D module from mpl_toolkits, which enables 3D plotting in matplotlib.

 2. Set Number of Points for the Spiral

n = 1000

n = 1000: Defines the number of points (or "steps") you want along the helix. The higher the value of n, the smoother the curve will appear because there will be more data points in the plot.

 3. Create Parametric Equation for the Helix

t = np.linspace(0, 10 * np.pi, n) 

x = np.sin(t)

y = np.cos(t) 

z = t 

t = np.linspace(0, 10 * np.pi, n):

 np.linspace(0, 10 * np.pi, n) generates n evenly spaced values of t between 0 and 10ฯ€. The t values represent the angle (or "time") along the helix as it twists. This range will make the helix loop several times.

 x = np.sin(t):

 The x coordinates of the helix are given by the sine of t. This creates a horizontal oscillation in the X direction (wave-like movement).

 y = np.cos(t):

 The y coordinates are given by the cosine of t. This works alongside the sine to create a circular motion around the Z-axis, giving the 3D spiral its shape.

 z = t:

 The z coordinates simply follow the values of t, which means the helix rises (or spirals) upward as t increases. The Z-axis is the height of the spiral.

 4. Set Up the Plot

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

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

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

 Creates a new figure for the plot. The figsize argument defines the dimensions of the plot (10 inches wide and 6 inches tall).

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

 Adds a 3D subplot to the figure. The 111 means "1 row, 1 column, 1st subplot" (in this case, there's only one plot).

 projection='3d' tells matplotlib that you want to create a 3D plot.

 5. Plot the Helix

ax.plot(x, y, z, color='purple', lw=2)

ax.plot(x, y, z, color='purple', lw=2):

 This function plots the x, y, and z coordinates in 3D space.

 color='purple': Sets the color of the helix line to purple.

 lw=2: Sets the line width to 2 (makes the line a little thicker, which makes it stand out more).

 6. Set Titles and Labels for the Axes

ax.set_title('3D Parametric Helix (DNA Spiral)', fontsize=16)

ax.set_xlabel('X axis')

ax.set_ylabel('Y axis')

ax.set_zlabel('Z axis')

ax.set_title('3D Parametric Helix (DNA Spiral)', fontsize=16):

 Adds a title to the plot: "3D Parametric Helix (DNA Spiral)", and sets the font size to 16.

 ax.set_xlabel('X axis'): Labels the X-axis as "X axis".

 ax.set_ylabel('Y axis'): Labels the Y-axis as "Y axis".

 ax.set_zlabel('Z axis'): Labels the Z-axis as "Z axis".

 These labels are displayed on the plot to indicate which axis corresponds to which dimension in the 3D space.

 7. Display the Plot

plt.show()

plt.show(): Displays the plot. This is the final step that actually renders the 3D helix and opens it in a plotting window.

 


Apollonian Gasket Pattern using Python

 


import matplotlib.pyplot as plt

import numpy as np

def draw_circle(ax, x, y, r):

    circle = plt.Circle((x, y), r, edgecolor='black', facecolor='none')

    ax.add_patch(circle)

def apollonian(ax, x, y, r, depth):

    if depth == 0:

        return

    draw_circle(ax, x, y, r)

    new_radius = r / 2

    apollonian(ax, x - r, y, new_radius, depth-1)

    apollonian(ax, x + r, y, new_radius, depth-1)

    apollonian(ax, x, y + r, new_radius, depth-1)

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

ax.set_aspect('equal', 'box')

ax.set_xlim(-1.5, 1.5)

ax.set_ylim(-1.5, 1.5)

initial_radius = 1

apollonian(ax, 0, 0, initial_radius, 5) 

ax.set_title('Apollonian Gasket')

plt.show()

#source code --> clcoding.com

Code Explanation:

1.Importing Necessary Libraries

import matplotlib.pyplot as plt

import numpy as np

matplotlib.pyplot: This is the main library for plotting 2D and 3D figures in Python. We're using it to create and display the plot.

numpy: This is a powerful numerical library in Python used for handling arrays and performing mathematical operations. It is useful for generating coordinate data.

 2. Drawing a Single Circle

def draw_circle(ax, x, y, r):

    circle = plt.Circle((x, y), r, edgecolor='black', facecolor='none')

    ax.add_patch(circle)

Purpose: This function draws a single circle on the plot.

x, y: Coordinates of the circle's center.

r: Radius of the circle.

plt.Circle(): This creates a circle object at the given position with the specified radius. The edgecolor='black' ensures that the circle's edge is outlined in black, and facecolor='none' ensures that the circle has no fill color (transparent).

 3. Recursive Function to Create the Apollonian Gasket

def apollonian(ax, x, y, r, depth):

    if depth == 0:

        return

    # Draw the current circle

    draw_circle(ax, x, y, r)

   

    # Calculate the radius of the three new tangent circles

    new_radius = r / 2

   

    # Recursively draw the three smaller tangent circles

    apollonian(ax, x - r, y, new_radius, depth-1)

    apollonian(ax, x + r, y, new_radius, depth-1)

    apollonian(ax, x, y + r, new_radius, depth-1)

Purpose: This function is the core of generating the Apollonian Gasket. It starts by drawing a circle and then recursively creates three smaller tangent circles inside the original circle.

Key Steps:

Base case (Stopping condition): If the depth reaches 0, the recursion stops. This prevents the function from going into infinite recursion.

Drawing the Circle: The current circle is drawn using draw_circle().

Calculating New Radius: Each recursive step reduces the radius of the new circles to half of the current radius (new_radius = r / 2). This makes the fractal progressively smaller.

Recursive Calls: The function then calls itself three times:

x - r, y: Creates a circle to the left of the current circle.

x + r, y: Creates a circle to the right of the current circle.

x, y + r: Creates a circle above the current circle.

 4. Setting Up the Plot

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

ax.set_aspect('equal', 'box')

ax.set_xlim(-1.5, 1.5)

ax.set_ylim(-1.5, 1.5)

Purpose: Sets up the plotting area.

plt.subplots(figsize=(8, 8)): Creates a new plot with a figure size of 8x8 inches.

ax.set_aspect('equal', 'box'): Ensures the aspect ratio of the plot is equal, so circles are not distorted. It makes sure the X and Y axes have the same scale.

ax.set_xlim(-1.5, 1.5) and ax.set_ylim(-1.5, 1.5): These functions define the range of the X and Y axes. It ensures the circles are centered and visible within the plot.

 5. Calling the Recursive Function

initial_radius = 1

apollonian(ax, 0, 0, initial_radius, 5)  # Depth=5 for deeper recursion

Purpose: This line starts the recursion.

The initial_radius = 1 defines the radius of the first circle (the largest one).

apollonian(ax, 0, 0, initial_radius, 5): This call starts the fractal drawing from the center of the plot (0, 0) with an initial radius of 1, and a recursion depth of 5. The depth determines how many iterations of circles will be drawn. Higher depth values make the fractal more intricate.

 6. Displaying the Plot

ax.set_title('Apollonian Gasket')

plt.show()

ax.set_title('Apollonian Gasket'): Adds a title to the plot.

plt.show(): This line displays the plot on the screen.

 


Wormhole Twist 3D Pattern using Python


 import numpy as np

import matplotlib.pyplot as plt

from mpl_toolkits.mplot3d import Axes3D

theta = np.linspace(0, 25 * np.pi, 1500) 

z = np.linspace(-4, 4, 1500)              

r = 1 / (z**2 + 1) + 0.5  

x = r * np.sin(theta)

y = r * np.cos(theta)

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

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

ax.plot(x, y, z, color='lime', linewidth=2)

ax.scatter(x, y, z, c=theta, cmap='cool', s=2)

ax.set_title('Wormhole Twist 3D Pattern', fontsize=18, color='white')

ax.set_facecolor('black')

fig.patch.set_facecolor('black')

ax.grid(False)

ax.set_xticks([])

ax.set_yticks([])

ax.set_zticks([])

plt.show()

#source code --> clcoding.com

Code Explanation:

1. Importing Libraries

import numpy as np

import matplotlib.pyplot as plt

from mpl_toolkits.mplot3d import Axes3D

numpy → For numerical calculations.

 matplotlib.pyplot → For plotting.

 Axes3D → To enable 3D plotting.

 2. Generating Data for the Spiral Structure

a) Theta → Angle for Rotation

theta = np.linspace(0, 25 * np.pi, 1500)

Generates 1500 values from 0 to 25ฯ€.

 Controls how many circular rotations (25 rotations).

 Bigger theta range = More twists.

 b) Z → Vertical Height

z = np.linspace(-4, 4, 1500)

Generates 1500 points from -4 to 4.

 Controls vertical length of the wormhole.

 c) Radius → Controls Distance from Center

r = 1 / (z**2 + 1) + 0.5

Formula gives a shape of a wormhole or funnel.

 Center is wider, ends are narrower.

 As z increases (top & bottom), r decreases.

 Why this formula?

 1 / (z² + 1) → Makes radius smaller at the top/bottom and bigger near the center (z=0).

 +0.5 → Adds minimum radius to avoid collapse to zero.

 3. Convert Polar to Cartesian Coordinates

x = r * np.sin(theta)

y = r * np.cos(theta)

Converts from (r, ฮธ) to (x, y) for 3D plotting.

 4. Creating Plot Environment

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

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

Creates the figure and 3D axis.

5. Plotting the Wormhole Spiral Line

ax.plot(x, y, z, color='lime', linewidth=2)

Draws the spiral line.

 Color → lime green.

 Line thickness → 2.

 6. Adding Scatter Dots (Glow Effect)

ax.scatter(x, y, z, c=theta, cmap='cool', s=2)

Adds tiny dots along the spiral line.

 c=theta → Color depends on theta (angle).

 cmap='cool' → Gradient color (cyan to magenta).

 s=2 → Dot size.

 Effect:

Looks like energy particles swirling around the wormhole.

 7. Styling the Plot

ax.set_title('Wormhole Twist 3D Pattern', fontsize=18, color='white')

ax.set_facecolor('black')

fig.patch.set_facecolor('black')

ax.grid(False)

Adds the title in white color.

Sets background color to black for a space-like look.

Removes grid lines.

8. Removing Axis Ticks

ax.set_xticks([])

ax.set_yticks([])

ax.set_zticks([])

Hides x, y, z axis numbers for a clean visual design.

9. Display the Final 3D Plot

plt.show()

Displays the 3D plot.


Python Coding Challange - Question with Answer (01160425)

 


Let's break down this Python code step by step:


import array as arr
  • This imports Python's built-in array module and gives it the alias arr.

  • The array module provides a space-efficient array (fixed-type) data structure, similar to lists but more efficient for large numeric data.



numbers = arr.array('i', [7, 8, -5])
  • This creates an array named numbers.

  • 'i' is the type code for signed integers (like int), meaning all elements in this array must be integers.

  • [7, 8, -5] is the list of integer values used to initialize the array.



print(numbers[1])
  • This prints the value at index 1 of the array.

  • In Python, indexing starts from 0. So:

    • numbers[0] → 7

    • numbers[1] → 8

    • numbers[2] → -5

Output: 8


Summary:

  • You're creating an integer array [7, 8, -5] and printing the second element (index 1), which is 8.


Application of Electrical and Electronics Engineering Using Python

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

Tuesday, 15 April 2025

Python Coding Challange - Question with Answer (01150425)

 


Explanation:

  • num = 6 sets num to 6.

  • decrement(num) calls the function, but num is passed by value (since integers are immutable in Python).

  • Inside the function, num -= 2 only affects the local variable. It doesn't change the original num.

  • So, print(num) still prints 6.

✅ Final Output:

6

400 Days Python Coding Challenges with Explanation

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

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

 


Code Explanation:

1. Defining the inner Generator Function
def inner():
    yield 1
    yield 2
inner() is a generator function, which means it returns an iterator when called.

It yields:

First: 1

Then: 2

2. Defining the outer Generator Function
def outer():
    yield from inner()
outer() is also a generator.

yield from inner() delegates to the inner() generator.

It automatically yields all values from inner(), one by one.

So outer() behaves just like inner() here.

3. Calling and Converting to a List
print(list(outer()))
outer() is called, returning a generator.

list(...) consumes the generator, collecting all yielded values into a list.

Output:
[1, 2]

4. Why yield from is Useful
It’s a cleaner, more readable way to re-yield values from a sub-generator.
Without yield from, you’d have to do:
def outer():
    for value in inner():
        yield value

Final Output

[1, 2]

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

 


Code Explanation:

1. Importing the asyncio Module
import asyncio
asyncio is Python’s built-in library for writing asynchronous code using the async/await syntax.

It's used for tasks like concurrent I/O operations (e.g., network requests, file reads).

2. Defining an Asynchronous Function f
async def f(x):
    return x * 2
This is an async function, meaning it returns a coroutine.

It takes an input x and returns x * 2.

Because there's no await inside, it's very fast and technically doesn't need to be async—but it's used here for demonstration or compatibility with other async code.

3. Defining the main Coroutine
async def main():
    r = await asyncio.gather(f(2), f(3))
    print(r)
This is another coroutine.

asyncio.gather(f(2), f(3)) runs both f(2) and f(3) concurrently.

await waits until both coroutines finish and returns their results as a list.

The result is printed: [4, 6].

4. Running the Event Loop
asyncio.run(main())
This starts the async event loop and runs the main() coroutine.
It blocks until main() is finished.


Final Output

[4, 6]

Sunday, 13 April 2025

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

 


Code Explanation:

1. Importing the lru_cache Decorator

from functools import lru_cache
lru_cache is a decorator from Python's functools module.

It stands for Least Recently Used cache.

It automatically stores the results of expensive function calls and reuses them when the same inputs occur again.

2. Using the @lru_cache Decorator

@lru_cache(maxsize=None)
This line decorates the fib function.

maxsize=None means the cache can grow without limit.

It helps speed up recursive functions like Fibonacci by memoizing results.

3. Defining the Recursive Fibonacci Function

def fib(n):
    if n < 2: return n
    return fib(n-1) + fib(n-2)
Base Case: If n is 0 or 1, return n.

Recursive Case: Return the sum of the two previous Fibonacci numbers:
fib(n-1) and fib(n-2).

4. Calling the Function and Printing Result

print(fib(5))
Calls the fib function with argument 5.

The function computes the 5th Fibonacci number:

fib(5) = fib(4) + fib(3)
       = (fib(3) + fib(2)) + (fib(2) + fib(1))
       = ...
       = 5
Result is 5, which is printed.

Final Output:

5


Popular Posts

Categories

100 Python Programs for Beginner (118) AI (152) 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 (217) Data Strucures (13) Deep Learning (68) 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 (186) Meta (24) MICHIGAN (5) microsoft (9) Nvidia (8) Pandas (11) PHP (20) Projects (32) Python (1218) Python Coding Challenge (884) Python Quiz (342) 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)