Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Sunday, 11 May 2025

3D Rose Surface Plot using Python

 


import numpy as np

import matplotlib.pyplot as plt

k=8

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

phi=np.linspace(0,np.pi,300)

theta,phi=np.meshgrid(theta,phi)

r = np.sin(k * theta) * np.sin(phi)

x = r * np.sin(phi) * np.cos(theta)

y = r * np.sin(phi) * np.sin(theta)

z = r * np.cos(phi)

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

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

surf=ax.plot_surface(x,y,z,cmap='inferno',edgecolor='none')

ax.set_title('3D Rose Surface Plot')

ax.axis('off')

plt.show()

#source code --> clcoding.com 

Code Explanation:

1. Import Libraries

import numpy as np

import matplotlib.pyplot as plt

numpy: For numerical calculations and creating coordinate grids.

 matplotlib.pyplot: For plotting the 3D surface.

 2. Set the Parameter

k = 5  # Number of petals (can be any float or integer)

The variable k controls the number of "petals" in the rose pattern.

 A higher or fractional k gives more complex shapes.

 3. Create Meshgrid for Angles

theta = np.linspace(0, 2 * np.pi, 300)  # Azimuthal angle

phi = np.linspace(0, np.pi, 300)        # Polar angle

theta, phi = np.meshgrid(theta, phi)

theta: Goes from 0 to

2π, wrapping around the z-axis (like longitude).

phi: Goes from 0 to

π, spanning from top to bottom of the sphere (like latitude).

np.meshgrid creates a grid of angle values used for surface plotting.

 4. Define the Rose Function

r = np.sin(k * theta) * np.sin(phi)

This defines the radius r at each angle based on the polar rose formula:

 r(θ,ϕ)=sin(kθ)sin(ϕ)

sin(kθ) makes the petal pattern.

 sin(φ) ensures the pattern wraps over the sphere rather than staying flat.

 5. Convert to 3D Cartesian Coordinates

 x = r * np.sin(phi) * np.cos(theta)

y = r * np.sin(phi) * np.sin(theta)

z = r * np.cos(phi)

This converts spherical coordinates

(r,θ,ϕ) to Cartesian coordinates (x,y,z):

 x=rsin(ϕ)cos(θ)

y=rsin(ϕ)sin(θ)

z=rcos(ϕ)

 This gives a 3D shape based on the rose function wrapped over a sphere.

 6. Plot the Surface

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

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

surf = ax.plot_surface(x, y, z, cmap='inferno', edgecolor='none')

Creates a 3D plot (projection='3d').

 plot_surface() draws the rose surface using x, y, z.

 cmap='inferno' adds color based on height/intensity.

 edgecolor='none' smooths the surface by hiding grid lines.

 7. Final Touches

ax.set_title(f"3D Rose Surface Plot (k = {k})")

ax.axis('off')

plt.show()

Adds a title showing the value of k.

 Turns off axis for a clean visual.

 


Petal Swirl Matrix using Python

 

import numpy as np

import matplotlib.pyplot as plt

from mpl_toolkits.mplot3d import Axes3D

def petal_shape(k, theta):

    return np.sin(k * theta)

k_values = np.linspace(2, 7, 20)  

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

theta_grid, k_grid = np.meshgrid(theta, k_values)

r = petal_shape(k_grid, theta_grid)

x = r * np.cos(theta_grid)

y = r * np.sin(theta_grid)

z = k_grid  

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

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

ax.set_facecolor('black')

surface = ax.plot_surface(x, y, z, cmap='spring', edgecolor='none', alpha=0.95)

ax.set_title("Petal Swirl Matrix", color='white', fontsize=18)

ax.axis('off')

fig.colorbar(surface, shrink=0.5, aspect=10)

ax.view_init(elev=45, azim=135)

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 (as np): For numerical calculations and handling arrays.

matplotlib.pyplot (as plt): For creating visual plots (2D and 3D).

Axes3D: This is necessary for 3D plotting with matplotlib.

2. Defining the Petal Shape Function
def petal_shape(k, theta):
    return np.sin(k * theta)
petal_shape(k, theta): This function generates a petal shape for the pattern, based on the frequency parameter k and angle theta. It returns the radial distance r as a function of k and theta (sinusoidal oscillation).

3. Defining Parameters and Generating Grids
k_values = np.linspace(2, 7, 20)  
theta = np.linspace(0, 2 * np.pi, 400)
theta_grid, k_grid = np.meshgrid(theta, k_values)
k_values: Creates an array of 20 values ranging from 2 to 7 for the frequency parameter k.

theta: Creates an array of 400 equally spaced values for the angle theta from 0 to 
2π.

meshgrid: Creates a 2D grid of coordinates for theta and k that will be used to evaluate the petal_shape function over all combinations.

4. Generating the Radial Distance (r)
r = petal_shape(k_grid, theta_grid)
r: Uses the petal_shape function to calculate the radial distance for each (k, theta) pair. This produces the petal-like oscillations for different values of k.

5. Converting to Cartesian Coordinates
x = r * np.cos(theta_grid)
y = r * np.sin(theta_grid)
z = k_grid  
x and y: Convert the polar coordinates (r, theta) to Cartesian coordinates.
x=rcos(θ)
y=rsin(θ)

z: Set the z coordinate to the k values, so each petal is positioned at a different height based on k.

6. Creating the 3D Plot
fig = plt.figure(figsize=(6, 6))
ax = fig.add_subplot(111, projection='3d')
fig: Creates a new figure with a size of 6x6 inches.
ax: Adds a 3D subplot to the figure for plotting the surface.

7. Setting Plot Aesthetics
ax.set_facecolor('black')
surface = ax.plot_surface(x, y, z, cmap='spring', edgecolor='none', alpha=0.95)
ax.set_facecolor('black'): Sets the background color of the plot to black.
plot_surface: Plots the surface with:
cmap='spring': A spring-like color map for surface coloring.
edgecolor='none': Removes the edges of the surface grid.
alpha=0.95: Sets the surface to be slightly transparent.

8. Adding Title and Customizing Axes
ax.set_title("Petal Swirl Matrix", color='white', fontsize=18)
ax.axis('off')
ax.set_title: Adds the title "Petal Swirl Matrix" in white color and with a font size of 18.
ax.axis('off'): Hides the axes for a cleaner look.

9. Adding a Colorbar
fig.colorbar(surface, shrink=0.5, aspect=10)
Adds a color bar to the plot to show the color mapping used for the surface, with shrink=0.5 to reduce its size and aspect=10 to adjust its aspect ratio.

10. Adjusting the View Angle
ax.view_init(elev=45, azim=135)
view_init: Sets the initial view of the plot, with:
elev=45: Elevation angle of 45° (view from above).
azim=135: Azimuthal angle of 135° (rotates the view around the z-axis).

11. Displaying the Plot
plt.show()
plt.show(): Renders and displays the final 3D plot.


Coral Torus Bloom Pattern using Python

 

import numpy as np

import matplotlib.pyplot as plt

from mpl_toolkits.mplot3d import Axes3D

u=np.linspace(0,2*np.pi,100)

v=np.linspace(0,2*np.pi,100)

u,v=np.meshgrid(u,v)

R=1

r=0.3

bloom=0.1*np.sin(5*u)*np.cos(7*v)

x=(R+r*np.cos(v)+bloom)*np.cos(u)

y=(R+r*np.cos(v)+bloom)*np.sin(u)

z=r*np.sin(v)+bloom

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

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

ax.set_facecolor('black')

surface = ax.plot_surface(x, y, z, cmap='plasma', edgecolor='none', alpha=0.95)

ax.set_xlim([-1.5,1.5])

ax.set_ylim([-1.5,1.5])

ax.set_zlim([-1.5,1.5])

ax.axis('off')

fig.colorbar(surface,shrink=0.5,aspect=10)

plt.title('Coral Torus Bloom',color='white',fontsize=18)

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 (as np): Used for numerical operations and array manipulations.

matplotlib.pyplot (as plt): Used for plotting 2D/3D graphics.

Axes3D: Enables 3D plotting in matplotlib.

2. Creating Meshgrid Parameters

u = np.linspace(0, 2 * np.pi, 100)

v = np.linspace(0, 2 * np.pi, 100)

u, v = np.meshgrid(u, v)

u and v: Arrays of 100 values evenly spaced from 0 to 

2π, representing angles.

meshgrid: Creates 2D coordinate grids from u and v for parameterizing a surface.

3. Defining Torus Parameters and Surface Perturbation

R = 1     

r = 0.3   

bloom = 0.1 * np.sin(5 * u) * np.cos(7 * v)

R: Major radius (distance from center of tube to center of torus).

r: Minor radius (radius of the tube).

bloom: A sinusoidal perturbation to add organic "bloom" effects to the torus surface, like coral growth.

4. Parametric Equations of the Deformed Torus

x = (R + r * np.cos(v) + bloom) * np.cos(u)

y = (R + r * np.cos(v) + bloom) * np.sin(u)

z = r * np.sin(v) + bloom

These are the parametric equations of a torus modified by the bloom effect:

x=(R+rcos(v)+bloom)cos(u)

y=(R+rcos(v)+bloom)sin(u)

z=rsin(v)+bloom

5. Creating the 3D Plot

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

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

fig: Creates a new figure window of size 6x6 inches.

ax: Adds a 3D subplot to the figure.

6. Plot Settings and Aesthetics

ax.set_facecolor('black')

surface = ax.plot_surface(x, y, z, cmap='plasma', edgecolor='none', alpha=0.95)

ax.set_facecolor: Sets the background of the 3D plot to black.

plot_surface: Plots the deformed torus surface with:

cmap='plasma': Color map for surface coloring.

edgecolor='none': No mesh lines.

alpha=0.95: Slight transparency.

7. Setting Plot Limits and Hiding Axes

ax.set_xlim([-1.5, 1.5])

ax.set_ylim([-1.5, 1.5])

ax.set_zlim([-1.5, 1.5])

ax.axis('off')

These limit the 3D view range for x, y, z axes and hide the axis grid and ticks for a cleaner look.

8. Adding Colorbar and Title

fig.colorbar(surface, shrink=0.5, aspect=10)

plt.title("Coral Torus Bloom", color='white', fontsize=18)

Adds a color bar to indicate surface value mappings.

Sets the title of the plot with white text.

9. Displaying the Plot

plt.show()

Renders the final 3D visualization.


3D Simulated Fireball using Python


import numpy as np

import matplotlib.pyplot as plt

from mpl_toolkits.mplot3d import Axes3D

n = 5000

r = np.random.rand(n) ** 0.5  

theta = np.random.uniform(0, 2 * np.pi, n)

phi = np.random.uniform(0, np.pi, n)

x = r * np.sin(phi) * np.cos(theta)

y = r * np.sin(phi) * np.sin(theta)

z = r * np.cos(phi)

intensity = 1 - rs

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

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

sc = ax.scatter(x, y, z, c=intensity, cmap='hot', s=2, alpha=0.8)

ax.set_title("3D Simulated Fireball")

ax.set_xlabel("X")

ax.set_ylabel("Y")

ax.set_zlabel("Z")

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

plt.tight_layout()

plt.show()

#source code --> clcoding.com 

Code Explanation:

1. Import Required Libraries
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
numpy: For math operations and random number generation.

matplotlib.pyplot: For plotting.

Axes3D: Enables 3D plotting using matplotlib.

2. Define Parameters and Generate Random Points in Spherical Coordinates
n = 5000  # Number of particles in the fireball
r = np.random.rand(n) ** 0.5  
Generates 5000 random radii from the origin.

** 0.5 makes particles denser toward the center, like a real fireball.

3. Generate Random Angular Coordinates
theta = np.random.uniform(0, 2 * np.pi, n)
phi = np.random.uniform(0, np.pi, n)
theta: Random azimuthal angle around the Z-axis (0 to 2π).

phi: Polar angle from the vertical axis (0 to π).

4. Convert Spherical to Cartesian Coordinates
x = r * np.sin(phi) * np.cos(theta)
y = r * np.sin(phi) * np.sin(theta)
z = r * np.cos(phi)
Converts spherical (r, theta, phi) to 3D Cartesian coordinates (x, y, z) to plot in 3D space.

5. Define Fireball Intensity (Brighter at Core)
intensity = 1 - r
Points closer to the center (r ≈ 0) are brighter (intensity ≈ 1).

Points near the edge fade out (intensity ≈ 0).

6. Set Up 3D Plotting Area
fig = plt.figure(figsize=(6, 6))
ax = fig.add_subplot(111, projection='3d')
Sets up a 3D subplot with a square figure size.

7. Plot the Fireball with Color Mapping
sc = ax.scatter(x, y, z, c=intensity, cmap='hot', s=2, alpha=0.8)
scatter: Plots all points in 3D.

c=intensity: Colors depend on how close the point is to the center.

cmap='hot': Uses a red-orange-yellow gradient like real fire.

s=2: Small point size for a glowing cluster.

alpha=0.8: Slight transparency for blending.

8. Add Labels and Aesthetics
ax.set_title("3D Simulated Fireball")
ax.set_xlabel("X")
ax.set_ylabel("Y")
ax.set_zlabel("Z")
ax.set_box_aspect([1, 1, 1])
Title and axis labels.

set_box_aspect([1, 1, 1]): Ensures equal scaling in all directions (spherical symmetry).

9. Show the Plot
plt.tight_layout()
plt.show()
tight_layout(): Adjusts spacing.

show(): Displays the final plot.


 

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


 Code Explanation:

 Line 1 – Create an empty list
funcs = []
Initializes an empty list named funcs.

This list will be used to store functions (lambdas).

 Lines 2–3 – Append lambdas inside a loop

for i in range(3):
    funcs.append(lambda: i)
range(3) gives i = 0, 1, 2

Each time, a lambda function is created and added to the list.

BUT: The lambda captures i by reference, not value.

This means all the lambdas share the same i, which changes during each loop iteration.

After the loop ends, i = 2, and all lambdas "remember" that final value.

 Line 4 – Call all stored functions
results = [f() for f in funcs]
This calls each lambda in funcs.

Since all lambdas reference the same variable i, and i == 2 after the loop:

Each f() returns 2

 Line 5 – Print the result
print(results)

Output:
[2, 2, 2]


Saturday, 10 May 2025

3D Parametric Shell Surface using Python

 


import numpy as np

import matplotlib.pyplot as plt

a = 1

b = 0.2

u = np.linspace(0, 2 * np.pi, 100)

v = np.linspace(0, 4 * np.pi, 100)

u, v = np.meshgrid(u, v)

X = a * (1 - v / (2 * np.pi)) * np.cos(v) * np.cos(u)

Y = a * (1 - v / (2 * np.pi)) * np.cos(v) * np.sin(u)

Z = a * (1 - v / (2 * np.pi)) * np.sin(v) + b * u

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

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

ax.plot_surface(X, Y, Z, cmap='magma', edgecolor='k', alpha=0.9)

ax.set_title("3D Parametric Shell Surface")

ax.set_xlabel("X axis")

ax.set_ylabel("Y axis")

ax.set_zlabel("Z axis")

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

plt.tight_layout()

plt.show()

#source code --> clcoding.com 

Code Explanation:

1. Import Libraries

import numpy as np

import matplotlib.pyplot as plt

numpy: Used for numerical computations and creating arrays.

 matplotlib.pyplot: Used for plotting 2D and 3D visualizations.

 2. Define Constants for Shape Control

a = 1

b = 0.2

a: Controls the overall scale of the shell surface.

 b: Adds a vertical twist/extension as the surface rotates.

 3. Create Parameter Grids (u and v)

u = np.linspace(0, 2 * np.pi, 100)

v = np.linspace(0, 4 * np.pi, 100)

u, v = np.meshgrid(u, v)

u: Angle around the circular cross-section (like the shell's rim).

 v: Controls the spiral motion (shell’s growth).

 np.meshgrid: Creates a grid for evaluating parametric equations over 2D domains.

 4. Define Parametric Equations

X = a * (1 - v / (2 * np.pi)) * np.cos(v) * np.cos(u)

Y = a * (1 - v / (2 * np.pi)) * np.cos(v) * np.sin(u)

Z = a * (1 - v / (2 * np.pi)) * np.sin(v) + b * u

These equations generate a spiraling and shrinking shell surface:

 X and Y: Determine the radial coordinates; they shrink over v.

 Z: Adds a vertical twist via b * u, and height via sin(v).

 The structure gets smaller as v increases, mimicking how a shell tightens inward.

 5. Set Up 3D Plotting

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

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

Initializes a 3D plot.

 figsize=(10, 8): Sets the size of the figure.

 6. Plot the Shell Surface

ax.plot_surface(X, Y, Z, cmap='magma', edgecolor='k', alpha=0.9)

plot_surface: Draws the parametric surface in 3D.

 cmap='magma': Uses a vibrant color map.

 edgecolor='k': Adds black edges for clarity.

 alpha=0.9: Slight transparency for smoother visuals.

  7. Customize Plot Appearance

ax.set_title("3D Parametric Shell Surface")

ax.set_xlabel("X axis")

ax.set_ylabel("Y axis")

ax.set_zlabel("Z axis")

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

Adds axis labels and title.

 8. Display the Plot

plt.tight_layout()

plt.show()

tight_layout(): Avoids label overlaps.

 show(): Renders the 3D plot.


Friday, 9 May 2025

Python for Everyone: Coding, Data Science & ML Essentials syllabus

 


Week 1: Introduction to Coding and Python

Topic: Introduction to coding and Python
Details:

  • Overview of programming concepts and Python's significance

  • Installing Python and setting up the development environment

  • Introduction to IDEs like PyCharm, VS Code, or Jupyter Notebooks


Week 2: Variables and Data Types

Topic: Understanding variables and data types
Details:

  • Variables: Naming conventions and assignment

  • Data types: strings, integers, floats, and booleans

  • Simple calculations and printing output


Week 3: User Interaction

Topic: Using the input() function for user interaction
Details:

  • Reading user input

  • Converting input types

  • Using input in simple programs


Week 4: Decision Making with If-Else Statements

Topic: Basic if-else statements for decision-making
Details:

  • Syntax and structure of if, elif, and else

  • Nested if-else statements

  • Practical examples and exercises


Week 5: Introduction to Loops

Topic: Introduction to loops for repetitive tasks
Details:

  • While loops: syntax and use cases

  • For loops: syntax and use cases

  • Loop control statements: break, continue, and pass

  • Simple loop exercises


Week 6: Functions and Code Organization

Topic: Introduction to functions
Details:

  • Definition and syntax of functions

  • Parameters and return values

  • The importance of functions in organizing code


Week 7: Built-in and User-Defined Functions

Topic: Exploring built-in functions and creating user-defined functions
Details:

  • Common built-in functions in Python

  • Creating and using user-defined functions

  • Scope and lifetime of variables


Week 8: Working with Lists

Topic: Understanding and using lists
Details:

  • Creating and modifying lists

  • List indexing and slicing

  • Common list operations (append, remove, pop, etc.)

  • List comprehensions


Week 9: String Manipulation

Topic: Introduction to string manipulation
Details:

  • String slicing and indexing

  • String concatenation and formatting

  • Common string methods (split, join, replace, etc.)


Week 10: Recap and Practice

Topic: Recap and practice exercises
Details:

  • Review of previous topics

  • Practice exercises and mini-projects

  • Q&A session for clarification of doubts


Week 11: Introduction to Dictionaries

Topic: Working with dictionaries for key-value data storage
Details:

  • Creating and accessing dictionaries

  • Dictionary methods and operations (keys, values, items, etc.)

  • Practical examples and exercises


Week 12: Working with Files

Topic: Reading and writing data to files
Details:

  • File handling modes (read, write, append)

  • Reading from and writing to files

  • Practical file handling exercises


Week 13: Exceptions and Error Handling

Topic: Introduction to exceptions and error handling
Details:

  • Understanding exceptions

  • Try, except, else, and finally blocks

  • Raising exceptions

  • Practical error handling exercises


Week 14: Introduction to Object-Oriented Programming

Topic: Basic introduction to OOP
Details:

  • Understanding classes and objects

  • Creating classes and objects

  • Attributes and methods

  • Practical examples of OOP concepts


Week 15: Final Recap and Practice

Topic: Recap and practice exercises
Details:

  • Comprehensive review of all topics

  • Advanced practice exercises and projects

  • Final Q&A and course completion


📊 Data Science & Machine Learning Extension

Week 16: Introduction to Data Science & Jupyter Notebooks

Topic: Getting started with Data Science
Details:

  • What is Data Science?

  • Setting up Jupyter Notebooks

  • Introduction to NumPy and Pandas

  • Loading and inspecting data


Week 17: Data Manipulation with Pandas

Topic: Data wrangling and cleaning
Details:

  • DataFrames and Series

  • Reading/writing CSV, Excel

  • Handling missing data

  • Filtering, sorting, grouping data


Week 18: Data Visualization

Topic: Exploring data visually
Details:

  • Plotting with Matplotlib

  • Advanced visuals using Seaborn

  • Histograms, scatter plots, box plots

  • Customizing graphs for insights


Week 19: Introduction to Machine Learning

Topic: Machine Learning fundamentals
Details:

  • What is ML? Types of ML (Supervised, Unsupervised)

  • Scikit-learn basics

  • Splitting data into training/testing sets

  • Evaluation metrics (accuracy, precision, recall)


Week 20: Building Your First ML Model

Topic: Creating a classification model
Details:

  • Logistic Regression or Decision Trees

  • Model training and prediction

  • Evaluating model performance

  • Model improvement basics


Week 21: Capstone Project & Course Wrap-up

Topic: Apply what you’ve learned
Details:

  • Real-world data project (e.g., Titanic, Iris, or custom dataset)

  • Full pipeline: load → clean → visualize → model → evaluate

  • Presentation and peer review

  • Final certification and next steps

Saturday, 3 May 2025

3D Butterfly Wing (Mathematical Model) using Python

 


import matplotlib.pyplot as plt

import numpy as np

u=np.linspace(0,2*np.pi,100)

v=np.linspace(-np.pi/2,np.pi/2,100)

u,v=np.meshgrid(u,v)

x=np.sin(u)*(1+0.5*np.cos(v))*np.cos(v)

y=np.cos(u)*(1+0.5*np.cos(v))*np.cos(v)

z=np.sin(v)+0.2*np.sin(3*u)

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

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

ax.plot_surface(x,y,z,cmap='coolwarm',edgecolor='k',alpha=0.9)

ax.set_title('3D Butterfly Wing')

ax.set_xlabel('X axis')

ax.set_ylabel('Y axis')

ax.set_zlabel('Z axis')

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

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 trigonometric functions.

 matplotlib.pyplot: Used for creating the 3D plot.

 2. Creating Parameter Grids

u = np.linspace(0, 2 * np.pi, 100)

v = np.linspace(-np.pi / 2, np.pi / 2, 100)

u, v = np.meshgrid(u, v)

u: Controls the angular direction (think of it like horizontal spread of the wing).

 v: Controls the vertical sweep or curvature of the wings.

 meshgrid: Creates a 2D grid to evaluate the parametric surface over.

 3. Defining the Parametric Equations

x = np.sin(u) * (1 + 0.5 * np.cos(v)) * np.cos(v)

y = np.cos(u) * (1 + 0.5 * np.cos(v)) * np.cos(v)

z = np.sin(v) + 0.2 * np.sin(3 * u)

These equations build a curved, sinusoidal surface that resembles butterfly wings:

 x and y: Give a spiraling shape using a modified polar coordinate system.

 The term (1 + 0.5 * cos(v)) * cos(v) gives depth and curvature.

 z: Controls the vertical deformation, making the wings appear "flapping" or "wavy."

 sin(v) gives the main vertical structure.

 0.2 * sin(3 * u) adds a ripple or flutter pattern, mimicking wing detail.

 4. Setting Up the 3D Plot

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

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

Creates a square figure with a 3D plotting environment.

 5. Plotting the Surface

ax.plot_surface(x, y, z, cmap='coolwarm', edgecolor='k', alpha=0.9)

plot_surface: Draws the 3D shape.

 cmap='coolwarm': Uses a smooth gradient of blue to red.

 edgecolor='k': Adds a black gridline for better surface structure visibility.

 alpha=0.9: Slight transparency for softness.

 6. Customizing the Axes

ax.set_title('3D Butterfly Wings (Mathematical Model)', fontsize=14)

ax.set_xlabel('X axis')

ax.set_ylabel('Y axis')

ax.set_zlabel('Z axis')

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

Adds title and axis labels.

 set_box_aspect([1, 1, 0.5]): Makes the Z-axis compressed to enhance the wing appearance.

7. Show the Plot

plt.tight_layout()

plt.show()

tight_layout(): Adjusts padding between plot elements.

 show(): Displays the 3D plot.

 

 


Crack the Python Interview : 160+ Questions & Answers for Job Seekers (Crack the Interview Book 2)

 


Python has established itself as one of the most sought-after programming languages across industries — from web development to data science, automation to artificial intelligence. Whether you are a fresher or an experienced developer aiming for your next big role, technical interviews often pose a major challenge.

This is where the book "Crack the Python Interview: 160+ Questions & Answers for Job Seekers" (part of the Crack the Interview series) steps in. Designed specifically to prepare candidates for real-world Python interviews, this book offers an extensive collection of carefully selected questions and model answers.

Let’s explore this book in depth and understand how it can become a vital resource in your job preparation toolkit.

Objective of the Book

The primary goal of this book is to help Python job seekers get ready for technical interviews. It does this by:

Providing a broad range of Python interview questions, covering both fundamental and advanced topics.

Offering concise and practical answers that interviewers expect.

Helping readers understand core Python concepts deeply enough to handle variations of standard questions during interviews.

Rather than being a traditional Python learning book, it serves as a focused interview preparation guide — a “last-mile” tool to polish your knowledge and boost your confidence.

Structure and Organization

The book is logically divided into sections that mirror the kind of topics commonly covered in Python job interviews. Here's an overview of the key areas:

1. Python Basics

The book begins with questions about:

Python syntax and structure

Variables, data types, operators

Control flow (loops, conditionals)

Functions and scope

This section ensures the reader is grounded in the building blocks of Python — a crucial starting point for any role.

2. Object-Oriented Programming (OOP)

Covers essential topics such as:

Classes and objects

Inheritance and polymorphism

Encapsulation

Special methods like __init__, __str__, and operator overloading

OOP concepts are vital for technical interviews, especially for roles that emphasize software engineering principles.

3. Data Structures and Algorithms

Focuses on:

Lists, dictionaries, sets, tuples

Stack, queue, linked lists (Pythonic approaches)

Sorting and searching algorithms

Time and space complexity

Many interviews involve solving problems related to efficient data handling and manipulation, and this section prepares readers for such challenges.

4. Advanced Python Concepts

Delves into more sophisticated areas:

Generators and iterators

Decorators and context managers

Lambdas, map, filter, and reduce

Modules and packages

Memory management and garbage collection

Having a grasp of these topics often distinguishes candidates in technical interviews for mid to senior-level positions.

5. Error Handling

Discusses:

Try, except, else, finally blocks

Custom exception classes

Common pitfalls and error patterns

Effective error handling is often assessed in coding rounds and technical discussions.

6. Python Libraries and Frameworks

Briefly touches upon popular libraries such as:

pandas, numpy for data manipulation

flask, django for web development

Testing frameworks like unittest and pytest

While not in-depth tutorials, this exposure is crucial for real-world project discussions during interviews.

7. Coding Exercises and Logical Puzzles

Small Python programs

Logic puzzles using Python

Practical coding challenges that interviewers often use to test logical thinking and code efficiency

Unique Features of the Book

160+ Curated Questions: Carefully selected to cover not just rote knowledge but conceptual depth and practical application.

Concise, Interview-Ready Answers: Each answer is designed to be explained verbally in an interview scenario, striking a balance between brevity and completeness.

Coverage of Edge Cases: Highlights tricky aspects and common mistakes — for example, Python's mutable default arguments or the intricacies of object mutability.

Quick Revision Format: Designed to enable quick revisits before interviews or coding assessments.

Bridges Knowledge Gaps: Helps candidates identify weaker areas that might not surface until faced with real interview questions.

Strengths of the Book

Focused on Interview Success: It doesn’t waste time on lengthy explanations — perfect for candidates who already know Python but need sharp revision.

Comprehensive Range: Covers everything from Python 101 to advanced-level topics, making it useful for both entry-level and experienced developers.

Practical Perspective: The book emphasizes how to answer interview questions, not just what the answer is.

Accessible Language: Clear and simple explanations without unnecessary jargon.

Useful for Different Roles: Whether you're applying for a developer, automation engineer, backend engineer, or data analyst role, the book touches on the Python essentials relevant to each.

Who Should Use This Book?

This book is ideal for:

Job seekers preparing for Python-based interviews.

Students looking to succeed in campus placements.

Working professionals aiming to switch to Python-heavy roles.

Developers needing a structured revision tool before technical tests or whiteboard interviews.

It’s especially useful for people who have learned Python theoretically but need help connecting their knowledge to interview questions.

Kindle : Crack the Python Interview : 160+ Questions & Answers for Job Seekers (Crack the Interview Book 2)

Hard Copy : Crack the Python Interview : 160+ Questions & Answers for Job Seekers (Crack the Interview Book 2)


Final Thoughts

"Crack the Python Interview: 160+ Questions & Answers for Job Seekers" is a well-crafted, efficient, and highly practical guide for anyone serious about succeeding in Python interviews. By concentrating on likely interview questions, explaining them in a concise and understandable way, and highlighting important nuances, the book provides readers with a serious advantage in a competitive job market.

It’s not a textbook — it’s a strategic companion for technical interview preparation. For candidates looking to move quickly from theory to job offer, this book can serve as the perfect final-stage resource.

Friday, 2 May 2025

3D Plasma Wave Simulation using Python

 


import matplotlib.pyplot as plt

import numpy as np

from mpl_toolkits.mplot3d import Axes3D

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

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

z=np.linspace(-5,5,30)

X,Y,Z=np.meshgrid(x,y,z)

wave=np.sin(2*np.pi*X*10)*np.cos(2*np.pi*Y/10)*np.sin(2*np.pi*Z/10)

threshold=0.5

mask=np.abs(wave)>threshold

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

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

sc=ax.scatter(X[mask],Y[mask],Z[mask],c=wave[mask],cmap='plasma',s=15,alpha=0.8)

ax.set_title('3D Plasma Wave Simulation')

ax.set_xlabel('X axis')

ax.set_ylabel('Y axis')

ax.set_zlabel('Z axis')

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

fig.colorbar(sc,shrink=0.6,label='Wave Amplitude')

plt.tight_layout()

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

numpy: For numerical operations and generating arrays.

 matplotlib.pyplot: For plotting.

 mpl_toolkits.mplot3d: Enables 3D plotting with Axes3D.

 2. Define 3D Coordinate Grids

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

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

z = np.linspace(-5, 5, 30)

Creates evenly spaced values from -5 to 5 along each axis (30 points).

 These serve as the spatial coordinates in the 3D space.

 3. Create 3D Meshgrid

X, Y, Z = np.meshgrid(x, y, z)

np.meshgrid converts the 1D arrays into 3D coordinate grids.

 Each point in the 3D volume now has corresponding (X, Y, Z) coordinates.

 4. Define the Plasma Wave Function

wave = np.sin(2 * np.pi * X / 10) * np.cos(2 * np.pi * Y / 10) * np.sin(2 * np.pi * Z / 10)

A mathematical expression to simulate a 3D plasma wave.

 Combines sine and cosine functions to simulate oscillating wave patterns in space.

 5. Apply Wave Threshold Mask

threshold = 0.5

mask = np.abs(wave) > threshold

Sets a cutoff (threshold) to visualize only strong wave amplitudes.

 mask is a boolean array selecting only points where wave amplitude exceeds 0.5.

 6. Set Up the 3D Plot

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

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

Initializes a figure with a 3D subplot.

 7. Scatter Plot the Wave Points

sc = ax.scatter(X[mask], Y[mask], Z[mask], c=wave[mask], cmap='plasma', s=15, alpha=0.8)

Plots only the points that passed the threshold mask.

c=wave[mask]: Colors each point based on wave amplitude.

cmap='plasma': Uses a vibrant colormap.

 s=15: Sets the point size.

 alpha=0.8: Semi-transparent points for better 3D depth effect.

 8. Customize the Plot

ax.set_title('3D Plasma Wave Simulation')

ax.set_xlabel('X Axis')

ax.set_ylabel('Y Axis')

ax.set_zlabel('Z Axis')

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

Adds title and axis labels.

 set_box_aspect([1, 1, 1]): Ensures equal aspect ratio for proper 3D geometry.

 9. Add Colorbar and Show Plot

fig.colorbar(sc, shrink=0.6, label='Wave Amplitude')

plt.tight_layout()

plt.show()

Adds a color bar indicating amplitude values.

 tight_layout() adjusts spacing to prevent clipping.

 show() displays the final visualization.

 

 


Thursday, 1 May 2025

Statistics with Python. 100 solved exercises for Data Analysis (Your Data Teacher Books Book 1)

 


Statistics with Python – 100 Solved Exercises for Data Analysis

In the evolving world of data analysis, one skill remains timeless and fundamental: statistics. No matter how advanced your machine learning models or data pipelines are, a core understanding of statistics empowers you to make sound, interpretable decisions with data. One book that takes a unique approach to this subject is "Statistics with Python. 100 Solved Exercises for Data Analysis" by Your Data Teacher.

Unlike dense academic textbooks or broad theoretical overviews, this book positions itself as a hands-on guide, ideal for readers who want to build statistical intuition by applying concepts directly in Python.

Purpose and Audience

The book is tailored for:

Beginners in data science or analytics

Students studying statistics who want practical coding experience

Python programmers wanting to develop statistical understanding

Professionals seeking to upgrade from Excel or business intelligence tools to code-based analysis

Its objective is clear: make statistical thinking accessible and actionable through practical Python exercises.

It does not attempt to be a comprehensive treatise on statistics. Instead, it serves as a practice workbook, offering 100 problems with structured solutions that demonstrate how to use Python’s statistical and data-handling libraries effectively.

Book Structure and Flow

The book is logically structured and progresses from foundational to more applied topics. Here's a breakdown of its main sections:

1. Descriptive Statistics

This section lays the groundwork by focusing on measures that summarize data. Readers are introduced to core metrics like central tendency, variability, and data distribution characteristics. The solutions show how to compute and interpret these metrics using Python’s numerical libraries.

2. Probability and Distributions

This portion delves into the probabilistic foundations of data analysis. It covers probability distributions — both discrete and continuous — and explains concepts such as randomness, density functions, and the shape and behavior of data under various theoretical models.

3. Inferential Statistics

Here, the focus shifts from describing data to making judgments and predictions. Readers learn how to estimate population parameters, conduct hypothesis testing, and interpret significance levels. The book uses real-world logic to introduce tests such as t-tests and chi-square tests, helping readers understand when and why these tools are applied.

4. Correlation and Regression

This section is dedicated to exploring relationships between variables. By walking through correlation coefficients and linear regression modeling, it helps readers grasp the difference between correlation and causation and learn how to model simple predictive relationships.

5. Practical Data Analysis and Interpretation

Toward the end of the book, the exercises become more integrated and context-driven. This final section simulates the kind of challenges data analysts face in real projects — synthesizing techniques, interpreting results in business or research contexts, and visualizing insights.

 Teaching Approach

The strength of this book lies in its pedagogical approach:

Problem-Solution Format: Each exercise starts with a clear problem statement, followed by a step-by-step walkthrough of the solution. This scaffolding allows readers to understand both how and why a method works.

Progressive Complexity: Exercises are arranged to build on previous concepts. This makes the book suitable for sequential study, ensuring a solid foundation before moving to complex analysis.

Interpretation Over Memorization: While computation is central, the book repeatedly emphasizes understanding the meaning of results, not just the mechanics of calculation.

Library Familiarity: Readers gain experience using key Python libraries such as pandas, numpy, scipy, and visualization tools like matplotlib and seaborn. This also prepares them for working with real data in more complex environments.

Strengths of the Book

Practical Focus: Rather than overwhelming readers with abstract concepts, the book shows how statistics are used in actual data analysis workflows.

Compact and Accessible: The writing is concise and approachable. It's free of unnecessary jargon, making it friendly for self-learners and non-technical professionals.

Real Python Usage: Solutions are grounded in actual Python code, reinforcing programming skills while teaching statistics. It’s a dual-purpose resource that strengthens both areas.

Excellent for Reinforcement: The sheer volume of exercises makes this a powerful tool for practice. It's ideal for students preparing for exams or interviews where applied statistics are tested

Use Cases and Practical Value

This book is a great resource for:

Building confidence in applying statistical techniques

Practicing Python coding in a data analysis context

Preparing for technical interviews or data science bootcamps

Creating a structured self-study plan

Enhancing an academic course with additional problem-solving

It’s especially valuable for those who have taken an online course in statistics or Python and now want to solidify their skills through application.

Kindle : Statistics with Python. 100 solved exercises for Data Analysis (Your Data Teacher Books Book 1)

Hard Copy : Statistics with Python. 100 solved exercises for Data Analysis (Your Data Teacher Books Book 1)

Final Thoughts

"Statistics with Python. 100 Solved Exercises for Data Analysis" is a focused, hands-on guide that hits a sweet spot for learners who are tired of passive theory and want to do statistics. Its clear explanations and practical Python implementations make it an ideal companion for aspiring data analysts and self-taught programmers.

If your goal is to become statistically fluent while coding in Python, this book provides the daily practice and reinforcement you need. It won’t replace a full statistics curriculum, but it makes an excellent bridge between learning concepts and applying them to data problems.

Popular Posts

Categories

100 Python Programs for Beginner (117) AI (43) Android (24) AngularJS (1) Api (2) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (206) C (77) C# (12) C++ (83) Course (67) Coursera (256) Cybersecurity (25) Data Analysis (5) Data Analytics (6) data management (12) Data Science (152) Data Strucures (9) Deep Learning (22) Django (16) Downloads (3) edx (2) Engineering (14) Euron (29) Events (6) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Generative AI (12) Google (39) Hadoop (3) HTML Quiz (1) HTML&CSS (47) IBM (30) IoT (1) IS (25) Java (93) Java quiz (1) Leet Code (4) Machine Learning (88) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (4) Pandas (4) PHP (20) Projects (29) pyth (1) Python (1083) Python Coding Challenge (479) Python Quiz (145) Python Tips (5) Questions (2) R (70) React (6) Scripting (3) security (3) Selenium Webdriver (4) Software (17) SQL (42) UX Research (1) web application (8) Web development (4) web scraping (2)

Followers

Python Coding for Kids ( Free Demo for Everyone)