Sunday, 18 May 2025

Moon Crater Pattern using Python

 


import matplotlib.pyplot as plt

import numpy as np

from scipy.ndimage import gaussian_filter


size=500

terrain=np.zeros((size,size))

def add_crater(map,x0,y0,radius,depth):

    x=np.arange(map.shape[0])

    y=np.arange(map.shape[1])

    X,Y=np.meshgrid(x,y,indexing='ij')

    crater = -depth * np.exp(-(((X - x0)**2 + (Y - y0)**2) / (2 * radius**2)))

    map+=crater

num_craters=100

np.random.seed(42)

for _ in range(num_craters):

    x=np.random.randint(0,size)

    y=np.random.randint(0,size)

    radius=np.random.randint(5,25)

    depth=np.random.uniform(0.1,0.6)

    add_crater(terrain,x,y,radius,depth)

terrain=gaussian_filter(terrain,sigma=1)

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

plt.imshow(terrain,cmap='gray',origin='lower')

plt.title('Moon Crater Pattern using Python')

plt.axis('off')

plt.colorbar(label='Depth')

plt.tight_layout()

plt.show()

#source code --> clcoding.com 

Code Explanation:

Step 1: Import Libraries

import numpy as np

import matplotlib.pyplot as plt

from scipy.ndimage import gaussian_filter

numpy (as np): Used for numerical operations, creating arrays, and random number generation.

 matplotlib.pyplot (as plt): Used for creating and displaying the plot.

 scipy.ndimage.gaussian_filter: Used to smooth the terrain to make the craters look more natural (optional).

 Step 2: Initialize Base Terrain (Flat Moon Surface)

size = 500

terrain = np.zeros((size, size))

size = 500: Defines the grid size of the terrain, creating a 500x500 map of the surface.

 terrain = np.zeros((size, size)): Initializes a flat terrain of zeros (0), where each point represents the surface height (0 means the flat surface).

 Step 3: Function to Add a Crater

def add_crater(map, x0, y0, radius, depth):

    x = np.arange(map.shape[0])

    y = np.arange(map.shape[1])

    X, Y = np.meshgrid(x, y, indexing='ij')

    crater = -depth * np.exp(-(((X - x0)**2 + (Y - y0)**2) / (2 * radius**2)))

    map += crater

add_crater() is a function that adds a Gaussian-shaped crater to the map.

 x0, y0: The center of the crater (location of the impact).

 radius: The size of the crater (affects how quickly the depth decreases away from the center).

 depth: The depth of the crater.

 Inside the function:

 x = np.arange(map.shape[0]): Creates an array of x-coordinates for the grid (from 0 to the map width).

 y = np.arange(map.shape[1]): Creates an array of y-coordinates for the grid (from 0 to the map height).

 X, Y = np.meshgrid(x, y, indexing='ij'): Creates a 2D grid of coordinates based on x and y. X holds the x-coordinates, and Y holds the y-coordinates.

 crater = -depth * np.exp(-(((X - x0)**2 + (Y - y0)**2) / (2 * radius**2))): This is the Gaussian function that creates a depression centered at (x0, y0) with the specified radius and depth. The formula creates a bell-shaped curve that decays as you move away from the center, simulating the impact of a crater.

 map += crater: Adds the crater depression to the terrain.

 Step 4: Generate Random Craters

num_craters = 100

np.random.seed(42)  # Reproducibility

 for _ in range(num_craters):

    x = np.random.randint(0, size)

    y = np.random.randint(0, size)

    radius = np.random.randint(5, 25)

    depth = np.random.uniform(0.1, 0.6)

    add_crater(terrain, x, y, radius, depth)

num_craters = 100: Sets the number of craters to be added to the map. In this case, 100 random craters will be placed.

 np.random.seed(42): Sets the random seed for reproducibility. This ensures that the random number generator produces the same sequence of random numbers every time you run the code.

 The loop generates random crater parameters (x, y, radius, and depth):

 x = np.random.randint(0, size): Randomly selects the x-coordinate of the crater (within the grid's size).

 y = np.random.randint(0, size): Randomly selects the y-coordinate of the crater.

 radius = np.random.randint(5, 25): Randomly chooses a radius for the crater, between 5 and 25 units.

 depth = np.random.uniform(0.1, 0.6): Randomly selects a depth for the crater, between 0.1 and 0.6.

 add_crater(terrain, x, y, radius, depth): Calls the add_crater() function to add each randomly generated crater to the terrain.

 Step 5: Smooth the Terrain (Optional)

terrain = gaussian_filter(terrain, sigma=1)

gaussian_filter(terrain, sigma=1): Smooths the terrain slightly using a Gaussian filter.

 sigma=1: Controls the amount of smoothing (higher values result in more smoothing).

 This step is optional but can make the craters appear more natural, as it reduces harsh edges and makes the craters blend more smoothly with the surrounding terrain.

 Step 6: Plot the Cratered Surface

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

plt.imshow(terrain, cmap='gray', origin='lower')

plt.title("Moon Crater Pattern", fontsize=16)

plt.axis('off')

plt.colorbar(label="Depth")

plt.tight_layout()

plt.show()

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

 

plt.imshow(terrain, cmap='gray', origin='lower'):

 

terrain: The data to be visualized (the cratered surface).

 

cmap='gray': Uses a grayscale color map to visualize the depths. Lighter shades represent higher elevations, while darker shades represent lower elevations (craters).

 

origin='lower': Ensures that the origin of the plot is at the bottom-left, as is standard for most geographic data.

 

plt.title("Moon Crater Pattern", fontsize=16): Adds a title to the plot.

 

plt.axis('off'): Hides the axis lines and labels for a cleaner visualization.

 

plt.colorbar(label="Depth"): Adds a color bar to the side of the plot to show the depth values, so you can interpret the grayscale values in terms of depth.

 

plt.tight_layout(): Adjusts the layout to ensure the plot fits well in the figure without any clipping.

 

plt.show(): Displays the plot.

 


Lava Flow Map from Volcano Pattern using Python

 



import numpy as np

import matplotlib.pyplot as plt

size = 300

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

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

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

elevation = np.exp(-((X)**2 + (Y)**2))

distance = np.sqrt(X**2 + Y**2)

lava_flow = np.exp(-distance * 2) * elevation  

terrain_noise = 0.05 * np.random.rand(*lava_flow.shape)

lava_flow += terrain_noise

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

plt.imshow(lava_flow, cmap='hot', extent=[-5, 5, -5, 5], origin='lower')

plt.colorbar(label='Lava Flow Intensity')

plt.title("Lava Flow Map from Volcano", fontsize=16)

plt.xlabel("Distance East")

plt.ylabel("Distance North")

plt.grid(False)

plt.tight_layout()

plt.show()

#source code --> clcoding.com 

Code Explanation:

Step 1: Import Libraries

import numpy as np

import matplotlib.pyplot as plt

numpy (np): A powerful library for numerical computations. We use it here to create arrays and perform mathematical operations.

 matplotlib.pyplot (plt): A plotting library for visualizing data. We will use it to create the heatmap of the lava flow.

 Step 2: Define Grid for Terrain

size = 300

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

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

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

size = 300: We define the size of the grid. This will create a 300x300 grid of values (i.e., 300 points in both the x and y directions).

 np.linspace(-5, 5, size): This creates a 1D array of size points that are evenly spaced between -5 and 5 for both x and y axes. This represents the geographic area of the map.

 np.meshgrid(x, y): This converts the 1D arrays x and y into a 2D grid (X, Y). This grid represents the terrain coordinates, where each point corresponds to a position in the x-y plane.

 Step 3: Simulate the Volcano Peak (Elevation)

elevation = np.exp(-((X)**2 + (Y)**2))

This line creates a volcano peak at the center of the grid (at the point (0, 0)).

 The function np.exp(-((X)**2 + (Y)**2)) is a Gaussian function, which produces a bell-shaped curve. The center of this curve is at (0, 0), where the volcano's peak is located.

 At the center, the value is 1 (the highest point).

 As you move away from the center, the values decrease exponentially, simulating the decreasing elevation as you move away from the volcano.

 Step 4: Simulate Lava Flow

distance = np.sqrt(X**2 + Y**2)

lava_flow = np.exp(-distance * 2) * elevation

distance = np.sqrt(X**2 + Y**2): This calculates the distance from each point on the grid to the center (0,0), which is where the volcano is located. This helps determine how far each point is from the volcano's peak.

 np.exp(-distance * 2): This part simulates the lava flow. As lava moves farther from the volcano, it loses intensity (cools down). The exponential decay (np.exp(-distance * 2)) represents this cooling effect. The value is higher near the volcano and gradually decreases as the distance from the volcano increases.

lava_flow = np.exp(-distance * 2) * elevation: This line combines the lava flow decay (np.exp(-distance * 2)) with the volcanic peak (elevation). The lava is more intense around the peak and fades as it spreads outward, creating a more realistic lava flow pattern.

 Step 5: Add Terrain Noise (Optional)

terrain_noise = 0.05 * np.random.rand(*lava_flow.shape)

lava_flow += terrain_noise

np.random.rand(*lava_flow.shape): This generates a random noise array with the same shape as lava_flow. The values are between 0 and 1.

 0.05 * np.random.rand(*lava_flow.shape): The noise is scaled by 0.05 to ensure the noise isn't too overwhelming. This makes the lava flow look more irregular and natural.

 lava_flow += terrain_noise: The noise is added to the lava_flow array, creating small variations in the lava intensity across the grid.

 Step 6: Plot the Lava Flow Map

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

plt.imshow(lava_flow, cmap='hot', extent=[-5, 5, -5, 5], origin='lower')

plt.colorbar(label='Lava Flow Intensity')

plt.title("Lava Flow Map from Volcano", fontsize=16)

plt.xlabel("Distance East")

plt.ylabel("Distance North")

plt.grid(False)

plt.tight_layout()

plt.show()

plt.figure(figsize=(8, 6)): Creates a new figure with a size of 8x6 inches.

 plt.imshow(lava_flow, cmap='hot', extent=[-5, 5, -5, 5], origin='lower'):

 lava_flow: This is the data (lava flow map) that we want to visualize.

 cmap='hot': Specifies the color map for the heatmap. The 'hot' color map uses red, orange, and yellow to represent high values (hot lava) and black for low values (cool lava).

 extent=[-5, 5, -5, 5]: This defines the axis limits. The plot will show the terrain from -5 to 5 in both the x and y directions.

 origin='lower': This sets the origin of the plot to be in the lower-left corner (this is common for maps and geographical data).

 plt.colorbar(label='Lava Flow Intensity'): Adds a color bar to the right of the plot, showing the lava flow intensity values. The label explains what the color bar represents.

 plt.title("Lava Flow Map from Volcano", fontsize=16): Adds a title to the plot.

 plt.xlabel("Distance East"), plt.ylabel("Distance North"): Labels the x and y axes to represent East-West and North-South directions, respectively.

 plt.grid(False): Disables the grid lines on the plot for a cleaner image.

 plt.tight_layout(): Ensures that the layout is adjusted so that the elements (like labels) are properly spaced and not cut off.

plt.show(): Displays the plot.

 


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

 

Code Explanation:

1. Initialization
funcs = []

What it does:
Initializes an empty list called funcs.
This list will hold lambda functions.

2. Loop to Create Functions
for i in range(5):
What it does:
Starts a for loop that runs 5 times, with i taking values from 0 to 4.
Purpose:
For each value of i, the code creates a lambda function that captures that value.

3. Creating Lambda Functions with Default Arguments
    funcs.append(lambda x=i: x)
What it does:
Defines a lambda function: lambda x=i: x

x=i sets a default argument, capturing the current value of i at that iteration.

Then, the lambda is appended to the funcs list.

Why it works:
In Python, default arguments are evaluated at the time of function definition, not when the function is called.

This prevents the common issue where lambdas inside loops all reference the same final value.

 Example (what's really being created):
1st loop: lambda x=0: x → stores 0

2nd loop: lambda x=1: x → stores 1

5th loop: lambda x=4: x → stores 4

4. Calling Each Function
print([f() for f in funcs])
 What it does:
Uses a list comprehension to call each lambda function stored in funcs.

Since each lambda has a default x, we call f() with no arguments.

Each f() returns the value of x it captured earlier.

Iteration-wise behavior:
funcs[0]() → x=0 → returns 0

funcs[1]() → x=1 → returns 1

funcs[4]() → x=4 → returns 4

5. Final Output
[0, 1, 2, 3, 4]

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


 Code Explanation:

1. Function Definition

def get_funcs():

    return [lambda x=i: x*2 for i in range(3)]

What it does:

Defines a function get_funcs() that returns a list of lambda functions.

The list comprehension [lambda x=i: x*2 for i in range(3)] creates 3 lambdas:

Each lambda captures the current value of i using x=i as a default argument.

Each lambda, when called without arguments, will return x * 2.

What's inside the returned list:

Equivalent to:

[

  lambda x=0: x*2,

  lambda x=1: x*2,

  lambda x=2: x*2

]

Each lambda will return:

0 * 2 = 0

1 * 2 = 2

2 * 2 = 4

 2. Calling the Lambdas

results = [f() for f in get_funcs()]

What it does:

Calls each lambda function returned by get_funcs().

Each function f() uses its default argument x=i, and returns x*2.

Step-by-step:

f = lambda x=0: x*2 → f() → returns 0

f = lambda x=1: x*2 → f() → returns 2

f = lambda x=2: x*2 → f() → returns 4

Resulting list:

results = [0, 2, 4]

3. Print the Results

print(results)

Output:

[0, 2, 4]


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

 


Code Explanation:

1. funcs = []
What happens:
Creates an empty list named funcs that will later store lambda functions.

2. for i in range(3):
What happens:
Starts a loop where i takes values 0, 1, and 2 in sequence.

3. funcs.append(lambda i=i: i*i)
Key point: The lambda function is defined with a default argument i=i.

Why use i=i?
This binds the current value of i at each loop iteration to the lambda’s parameter i. It effectively “freezes” the value of i for that lambda.

What does the lambda do?
It returns i*i, the square of its argument i.
Effect:
Three lambda functions are created and appended to funcs:
First lambda has default i=0 → returns 0*0 = 0
Second lambda has default i=1 → returns 1*1 = 1
Third lambda has default i=2 → returns 2*2 = 4

4. for f in funcs:
What happens:
Iterates over each lambda function stored in funcs.

5. print(f())
What happens:
Calls each lambda function without any argument.
Because of default argument:
The lambda uses its default value of i captured during creation.

Output:
Prints the square of the captured i for each lambda:
0
1
4

Friday, 16 May 2025

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

 


Code Explanation:

1. Global Variable Declaration
x = 100
A global variable x is defined and set to 100.

2. Function Definition: func
def func():
A function func() is defined. It contains:

a local variable x = 200

an inner function inner() that prints 300

calls to inner() and print(x)

3. Inside func()
    x = 200
A new local variable x is declared inside func(), and its value is set to 200.

This does NOT affect the global x (x = 100 outside remains unchanged).

def inner(): print(300)
A nested function inner() is defined.

When called, it will print 300.

inner()
Calls the inner function.

Output:
300

print(x)
Prints the local variable x from func(), which is 200.

Output:
200

4. Call func()
func()
Executes all the code inside the function:

inner() → prints 300

print(x) inside func() → prints 200

5. Final Line: Print Global x
print(x)
This is outside of any function.

Refers to the global variable x = 100

Output:
100

Final Output:
300
200
100


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

 


Code Explanation:

1. Global Scope (x = 10)
x = 10
The first x = 10 creates a variable x in the global scope (outside any function).

This value of x is available throughout the entire program unless overridden in a local scope.

2. Defining outer()
def outer():
    x = 20
    def inner(): nonlocal x; x = 30
    inner(); print(x)
Inside outer(), there's another variable x = 20, which is local to outer(). This means that x inside the outer() function initially takes the value 20.

Defining the inner() function:

def inner(): nonlocal x; x = 30
inner() is a nested function inside outer().

The nonlocal x statement tells Python to look for x in the nearest enclosing scope (which is outer()), rather than creating a new x in inner().

The x = 30 changes the value of x in the enclosing outer() function to 30.

Calling inner():

inner(); print(x)
When inner() is called, it updates the value of x in the outer() function to 30.

After inner() runs, x inside outer() is now 30.

The print(x) inside outer() will print the value of x from the outer() scope, which is now 30.

3. Calling outer()
outer(); print(x)
Executing outer():

outer() is called, and inside it, x becomes 20 initially.

inner() runs and modifies x to 30.

So, the first print statement inside outer() prints 30.

The final print(x):

This print statement is outside outer(), so it refers to the global x.

The global x was never modified by outer(). It still holds the value 10.

Hence, this print statement prints 10.

Final Output
30
10


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

 


Code Explanation:

1. List Initialization
funcs = []
Creates an empty list named funcs.

This will store lambda functions.

2. For Loop to Append Lambdas
for i in range(3):
    funcs.append(lambda: i)
Breakdown:
range(3) produces: 0, 1, 2

On each iteration:

A lambda function is created: lambda: i

This function returns the value of i when it's called later.

This lambda is added to the funcs list.

 Important:
The lambda captures the variable i, not its value at that moment.

All 3 lambdas end up referring to the same i, which becomes 2 at the end of the loop.

So, this is not the same as storing lambda: 0, lambda: 1, and lambda: 2.

3. Call Each Lambda Function
for f in funcs:
    print(f())
Now, we loop through each function in funcs and call it.

But recall: each lambda refers to the same variable i, which is now 2.

So, this prints:

2
2
2

Final Output

2
2
2

Thursday, 15 May 2025

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


 Code Explanation:

1. Function Definition
def tricky(val, container={}):
This defines a function named tricky that takes two parameters:
val: a required argument.

container: an optional argument with a default value of an empty dictionary ({}).

Important Concept:
The default value for container is mutable (a dictionary). In Python, default mutable arguments are only evaluated once, at function definition time—not each time the function is called. This is key to the "trick" in this function.

2. Modify the Dictionary
    container[val] = True
This line adds a new key-value pair to the dictionary container.

The key is val, and the value is True.

For example, if val = 'a', it adds 'a': True to the dictionary.

3. Return the Dictionary
    return container
Returns the updated container dictionary.

4. First Function Call
print(tricky('a'))
The function is called with 'a' as the argument.
Since no second argument is passed, the default dictionary {} is used.
It adds 'a': True to the dictionary.
Returns {'a': True}.

Output:
{'a': True}

5. Second Function Call
print(tricky('b'))
The function is called with 'b' as the argument.
Again, no second argument is passed, so you might expect a fresh dictionary—but:

Python reuses the same default dictionary created during the first function call!

So now 'b': True is added to the same dictionary.

The dictionary now contains {'a': True, 'b': True}.

Output:
{'a': True, 'b': True}


Wednesday, 14 May 2025

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

 

Code Explanation:

 1. Function Definition
def append_to_list(value, my_list=[]):
Function Name: append_to_list

Parameters:

value: The item to add to the list.

my_list=[]: A default mutable argument, which is a list. This is the key part to focus on.

Important: Default values like [] are only evaluated once when the function is defined, not every time it’s called.

 2. Function Body
    my_list.append(value)
Adds the value to the my_list.

If no list is passed in, it appends to the default list (which is reused between calls).

    return my_list
Returns the updated list after appending the value.

3. First Function Call
print(append_to_list(1))
No list is provided, so the default list [] is used.

1 is appended to the list → list becomes [1].

Output:
[1]

4. Second Function Call
print(append_to_list(2))
Again, no list is provided.

But here's the catch: the same default list from the first call is reused.

2 is appended to the existing list [1], making it [1, 2].

Output:

[1, 2]

5. Final Output
[1]
[1, 2]

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

 


Code Explanation:

1. Function Definition
def add_entry(key, value, data={}):
Function Name: add_entry

Parameters:
key: The key to add to the dictionary.
value: The value to assign to the key.
data={}: A mutable default argument — this is important and causes unexpected behavior.

2. Function Logic
data[key] = value
return data
The function adds the key-value pair to the data dictionary.
Then it returns the updated dictionary.

3. Function Calls
print(add_entry('a', 1))
print(add_entry('b', 2))
This is where the mutable default argument issue shows up.

 4. What Happens Internally
First Call:
add_entry('a', 1)
data is the default {}.
'a': 1 is added.
Returns: {'a': 1}

Second Call:
add_entry('b', 2)
You might expect a new dictionary, but Python reuses the same data dictionary from the previous call.
'b': 2 is added to the same dictionary.
Returns: {'a': 1, 'b': 2}

5. Output
{'a': 1}
{'a': 1, 'b': 2}


Tuesday, 13 May 2025

Deep Learning with Python, Second Edition by Franรงois Chollet - Free PDF

 


A Must-Read for Aspiring AI Experts

If you’re serious about mastering deep learning and want a practical, hands-on guide that cuts through the complexity—look no further than Deep Learning with Python, Second Edition by Franรงois Chollet.

Authored by the creator of Keras and a leading engineer at Google, this extensively revised edition of the bestselling original dives deep into the mechanics and applications of deep learning using Python and TensorFlow. Whether you're just starting out or looking to sharpen your neural network skills, this book offers the clarity and depth needed to succeed.


๐Ÿ“˜ What You’ll Learn

This second edition is packed with new content and practical insights, covering key areas such as:

  • ๐Ÿง  Deep learning from first principles

  • ๐Ÿ–ผ️ Image classification & image segmentation

  • Time series forecasting

  • ๐Ÿ“ Text classification and machine translation

  • ๐ŸŽจ Text generation, neural style transfer, and image generation

Each topic is introduced with intuitive explanations, hands-on examples, and real-world applications that help you immediately put what you learn into practice.


๐Ÿš€ Why This Book Stands Out

Thousands have already learned deep learning through the first edition of this book. Now, with major updates and new topics, the second edition raises the bar even further:

  • Real-world examples make learning engaging and relevant

  • Theory + practice blend to give you both intuition and implementation skills

  • No advanced math or ML background needed — just intermediate Python skills

If you're a developer, data scientist, or tech enthusiast looking to break into AI, this book makes the seemingly complex world of deep learning accessible and actionable.


๐Ÿ’ก About the Technology

Recent breakthroughs in deep learning are revolutionizing how software understands text, images, speech, and more. With tools like Keras and TensorFlow, you can now build models for:

  • Automatic translation

  • Image and speech recognition

  • Predictive analytics

  • Generative art and much more

These technologies are no longer confined to research labs—they're powering products you use every day. And they’re well within your reach.


๐Ÿ“– What’s Inside

  • Foundations of deep learning and neural networks

  • Working with Keras and TensorFlow

  • Deep learning for vision, text, and time series

  • Generative models and style transfer

  • Best practices for real-world deployment

You also get the complete eBook (PDF, ePub, Kindle) with the purchase of the print edition—courtesy of Manning Publications.


๐Ÿ‘ค About the Author

Franรงois Chollet is a software engineer at Google and the creator of Keras, one of the most widely used deep-learning libraries in the world. His clear teaching style and deep expertise make this book a standout resource in the AI community.


๐Ÿ“š Table of Contents

  1. What is deep learning?

  2. The mathematical building blocks of neural networks

  3. Introduction to Keras and TensorFlow

  4. Getting started with neural networks

  5. Fundamentals of machine learning

  6. The universal workflow of machine learning

  7. Working with Keras: A deep dive

  8. Introduction to deep learning for computer vision

  9. Advanced deep learning for computer vision

  10. Deep learning for timeseries

  11. Deep learning for text

  12. Generative deep learning

  13. Best practices for the real world

  14. Conclusions


✅ Who Should Read This?

This book is perfect for:

  • Python developers with intermediate skills

  • Anyone curious about artificial intelligence

  • Professionals aiming to apply deep learning in real-world applications

No prior experience with Keras, TensorFlow, or machine learning is required.


๐ŸŽฏ Final Thoughts

Deep Learning with Python, Second Edition is more than just a book—it’s a practical blueprint to mastering modern AI. With accessible explanations, powerful tools, and hands-on projects, it’s your step-by-step guide to becoming a deep learning practitioner.

Grab your copy and start building the future.

FREE PDF: Deep Learning with Python (Second Edition)


Hard Copy: Deep Learning with Python, Second Edition


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

 


Code Explanation:

1. Class Definition
class A:
    def __init__(self):
        self.val = 1
This defines a class A.

The constructor __init__ is called when an object of class A is created.

It initializes the attribute val to 1.

2. Method Definition

def update(self):
    self.val += 1
This method increases the value of val by 1.

3. Object Creation
a = A()
An instance a of class A is created.

a.val is now 1.

4. Calling update()
a.update()
This increments a.val from 1 to 2.

5. Printing Value
print(a.val)
Prints the current value of a.val, which is now 2.

Final Output
2


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

 


Code Explanation:

1. Class Definition
class MyClass:
    def __init__(self, value):
        self.value = value
This defines a class named MyClass.

The __init__ method is a constructor, called when the object is created.

It takes one argument value, and sets self.value = value.

2. Object Creation
obj = MyClass(5)
An object obj of MyClass is created.

5 is passed to the constructor, so initially: obj.value = 5.

3. Overwriting Attribute

obj.value = 10
The value attribute is manually changed to 10 after object creation.

4. Printing the Attribute
print(obj.value)
Now it prints the updated value, which is 10.

Final Output
10

Monday, 12 May 2025

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

 


Code Explanation:

Function Definition
def append_to_list(val, list=[]):

What Happens:
A function named append_to_list is defined.
It takes two parameters:
val: the value to be added to a list.
list: an optional parameter, with a default value of an empty list [].

Append Value to List
    list.append(val)

What Happens:
The method append(val) adds the value val to the end of the list.
If no custom list was passed, it uses the shared default list, which keeps getting modified across function calls.

Return the Modified List
    return list

 What Happens:
The updated list is returned as the output of the function.

First Function Call
print(append_to_list(1))

What Happens:
No list is passed, so it uses the default list: [].
1 is appended → list becomes [1].
The default list is now modified and becomes [1].

Output:
[1]

Second Function Call
print(append_to_list(2, []))

What Happens:
A new empty list [] is passed.
2 is appended to this new list → list becomes [2].
The default list ([1]) is not affected here.

Output:
[2]

Third Function Call
print(append_to_list(3))

What Happens:
No list is passed again, so it uses the modified default list from the first call, which is now [1].
3 is appended → list becomes [1, 3].

Output:
[1, 3]

Final Output Summary
[1]
[2]
[1, 3]


Sunday, 11 May 2025

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

 


Code Explanation:

1. Function Definition: append_to_list(val, lst=[])
def append_to_list(val, lst=[]):
    lst.append(val)
    return lst
This function is defined with two parameters:

val: The value that will be appended to the list.

lst: The list to which the value will be added. It has a default value of an empty list [].

Important Concept: The parameter lst=[] uses a mutable default argument (a list). In Python, default mutable arguments (like lists, dictionaries) are not re-initialized every time the function is called. Instead, they are modified in-place across function calls.

2. First Function Call: append_to_list(1)
print(append_to_list(1))
Here, append_to_list(1) is called with val=1 and the default lst=[].

Since the list lst is empty initially, 1 is appended to it, changing lst to [1].

The function returns [1], and that is printed.

Output after first call:
[1]

3. Second Function Call: append_to_list(2)
print(append_to_list(2))
In the second call, append_to_list(2) is executed with val=2.

Now, because of the mutable default argument, the same list lst (from the previous call) is used again. This means the list now already contains [1] from the previous call.

The value 2 is appended to this list, updating it to [1, 2].

The function returns [1, 2], and that is printed.

Output after second call:
[1, 2]

4. Why Does This Happen?
Mutable Default Argument: The default value lst=[] is only initialized once when the function is defined. If the function is called multiple times and doesn't explicitly pass the lst argument, it keeps modifying the same list object. This is why in the second function call, the value 2 is appended to the same list that had 1 from the first call.

Mutable objects like lists, dictionaries are shared across function calls when used as default arguments.

5. Final Output
When the code is executed:
print(append_to_list(1))  # Output: [1]
print(append_to_list(2))  # Output: [1, 2]
The outputs printed are:

Final Output:

[1]
[1, 2]


The AI Workshop: The Complete Beginner's Guide to AI: Your A-Z Guide to Mastering Artificial Intelligence for Life, Work, and Business—No Coding Required

 


The AI Workshop: A Complete Beginner’s Guide to Artificial Intelligence (No Coding Needed)

Artificial Intelligence (AI) is no longer science fiction or the domain of software engineers. It’s real, it's here, and it's reshaping how we live, work, and do business. But for many beginners, the complexity and technical jargon can be overwhelming—especially for those with no programming background.

That’s where “The AI Workshop: The Complete Beginner's Guide to AI” comes in. This book serves as an A-to-Z, hands-on guide to understanding and applying AI, even if you've never written a single line of code. Whether you're a small business owner, a professional, or just curious about AI, this guide gives you practical tools to get started immediately.

Why AI Matters in Today’s World

AI is behind the smart assistants on your phone, the recommendations on Netflix, the spam filter in your email, and even the predictive text you're reading right now. It automates tasks, finds patterns in data, improves decision-making, and can significantly enhance productivity and creativity.

Yet, despite its wide applications, there's a misconception that AI is only for tech experts. In reality, you don't need to be a coder to understand or even use AI. That’s what this book emphasizes.

What This Book Offers (and Why It Stands Out)

The AI Workshop demystifies AI by breaking it down into digestible concepts. It’s designed around a practical framework, combining clear explanations, visual examples, and interactive exercises. Here’s what makes it special:

No Coding Required

You won’t need Python, Jupyter notebooks, or any machine learning libraries. The book uses real-world, low-code/no-code platforms like:

Google AutoML

Microsoft Power Automate

ChatGPT and GPT-based tools

AI writing and design tools (Jasper, Canva AI)

AI-powered analytics platforms (Tableau, Power BI with AI integrations)

Step-by-Step Workshops

Every chapter is formatted like a workshop, guiding you through actual use cases:

  • Build a chatbot with AI tools
  • Automate social media posts using AI schedulers
  • Use AI to summarize reports or emails
  • Generate customer insights from survey data
  • Create content using generative AI tools

Business Applications

Understand how AI can:

  • Automate customer support
  • Improve marketing campaigns
  • Predict customer churn
  • Enhance HR and recruitment
  • Streamline project management

Life Applications

Use AI to:

  • Plan your travel itineraries
  • Organize your daily tasks
  • Personalize your fitness routines
  • Manage finances through AI-enabled apps

Topics Covered in the Book

Here’s a glimpse of the book’s core sections:

1. What Is AI?

A beginner-friendly breakdown of AI, machine learning, deep learning, and how they all fit together.

2. Types of AI

Narrow AI vs General AI

Supervised vs Unsupervised Learning (explained visually)

Natural Language Processing (NLP)

Computer Vision basics

3. AI Tools You Can Use Today

Hands-on tutorials on:

ChatGPT and conversational AI

AI design generators (like DALL·E and Canva AI)

Data prediction without code (e.g., Google AutoML Tables)

4. How to Think Like an AI Designer

Problem framing

Understanding bias in AI

Ethical considerations

Human-AI collaboration (not competition)

5. AI for Business

AI for sales forecasting

Personalized customer experiences

AI-driven data dashboards

Automating repetitive back-office tasks

6. AI for Career Growth

Using AI to build your resume

Leveraging AI to learn faster

Preparing for an AI-powered job market

What You'll Gain

By the end of this book, readers will:

Understand key AI concepts and vocabulary

Know how to choose the right AI tool for a task

Be able to apply AI immediately to real-life or business challenges

Have the confidence to explore more advanced tools, even without coding

Who Is This Book For?

Entrepreneurs who want to automate and grow smarter

Professionals looking to increase productivity or pivot careers

Students and educators wanting to bring AI into classrooms or projects

Non-technical managers who oversee AI teams or projects

Curious learners who want to explore the future responsibly

Hard Copy : The AI Workshop: The Complete Beginner's Guide to AI: Your A-Z Guide to Mastering Artificial Intelligence for Life, Work, and Business—No Coding Required

Kindle : The AI Workshop: The Complete Beginner's Guide to AI: Your A-Z Guide to Mastering Artificial Intelligence for Life, Work, and Business—No Coding Required

Final Thoughts: AI Is a Tool, Not a Threat

The AI Workshop proves that you don’t have to be a tech genius to ride the AI wave. Instead, AI is a tool—one that can enhance your daily life, boost your work output, and unlock entirely new opportunities. Whether you’re running a business, climbing the career ladder, or just trying to work smarter, this guide helps you do exactly that—without needing to learn how to code.


It’s not about becoming an AI expert. It’s about becoming AI-literate, and using that knowledge to thrive in the world that’s already being shaped by it.


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.


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)