Saturday, 31 January 2026

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

 


Code Explanation:

1. Class Definition
class Tracker:

This line defines a class named Tracker.

It is used to track how many times objects are called.

2. Class Variable
    count = 0

count is a class variable, not an instance variable.

It is shared by all objects of the Tracker class.

Initial value of count is 0.

3. Callable Method (__call__)
    def __call__(self):


__call__ allows objects of this class to be called like a function.

Example: a() or b().

        Tracker.count += 1


Increases the class variable count by 1.

Since it belongs to the class, all objects see the same updated value.

        return Tracker.count


Returns the updated value of count.

4. Object Creation
a = Tracker()
b = Tracker()


Two separate objects a and b are created.

Both share the same class variable count.

5. First Call
a()


Tracker.count changes from 0 → 1

Returns 1

6. Second Call
b()


Tracker.count changes from 1 → 2

Returns 2

Even though b is a different object, it uses the same count.

7. Third Call
a()

Tracker.count changes from 2 → 3

Returns 3

8. Print Statement
print(a(), b(), a())

Prints the returned values in order:

1 2 3

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

 


Code Explanation:

1. Class Definition

class Accumulator:


This line defines a class named Accumulator.

A class is like a blueprint for creating objects.

2. Constructor Method (__init__)
    def __init__(self):
        self.v = 1

__init__ is a constructor that runs automatically when an object is created.

self refers to the current object.

self.v = 1 initializes an instance variable v with value 1.

Every object of Accumulator will start with v = 1.

3. Callable Method (__call__)
    def __call__(self, x):

__call__ makes the object callable like a function.

This means you can use the object with parentheses, e.g., a(2).

        self.v += x


Adds the value of x to the current value of self.v.

This updates the stored value inside the object.

        return self.v


Returns the updated value of v.

4. Object Creation
a = Accumulator()

Creates an object named a from the Accumulator class.

The constructor runs, so now:

a.v = 1

5. First Function Call
a(2)

Calls the __call__ method with x = 2.

Calculation:

v = 1 + 2 = 3

Returns 3.

6. Second Function Call
a(3)


Calls the same object again with x = 3.

Calculation:

Previous v = 3

v = 3 + 3 = 6

Returns 6.

7. Print Statement
print(a(2), a(3))


Prints the results of both calls.

Output:

3 6

Deep Roots — Book 2: Supervised Machine Learning: Series: Deep Roots: Machine Learning from First Principles (Book 2 of 8) (Deep Roots: Machine Learning ... not just how models work — but why they mu)

 


Machine learning has become essential in fields ranging from business analytics to scientific discovery. But most books on the topic focus on how algorithms work — often teaching recipes, code snippets, and formulas without grounding learners in the deeper intuition behind model behavior.

Deep Roots — Book 2: Supervised Machine Learning takes a different path. As the second volume in the Deep Roots: Machine Learning from First Principles series, this book emphasizes understanding why supervised learning models behave the way they do. Rather than treating them as black-box tools, it builds a conceptual foundation rooted in first principles — helping readers truly grasp the mechanics, assumptions, limitations, and real-world relevance of supervised learning.

If you want to go beyond surface-level knowledge and learn machine learning with clarity, confidence, and practical understanding, this book is designed to guide your journey.


Why Supervised Learning Matters

Supervised learning forms the backbone of many predictive systems used in industry and research. From customer churn prediction and credit scoring to medical diagnosis and image classification, supervised models are used wherever labeled data (inputs paired with known outputs) is available.

At its core, supervised learning teaches models to map inputs to outputs — but the deeper challenge isn’t just mapping, it’s reasoning about the conditions under which these mappings hold true, how models generalize beyond training data, and what trade-offs are involved in choosing one algorithm over another.

This book tackles those challenges head-on.


What You’ll Learn

1. Foundations of Supervised Learning

Before diving into specific algorithms, the book helps you understand the conceptual structure underlying all supervised learning:

  • What distinguishes supervised from unsupervised or reinforcement learning

  • The role of training and test data

  • How models learn patterns from examples

  • The difference between memorization and generalization

This foundational lens equips you to see commonalities across different algorithms instead of treating them as isolated techniques.


2. Key Algorithms Explored Deeply

Rather than presenting algorithms as recipes, the book explains:

  • Linear Regression: Why least squares works, how it approximates relationships, and what its assumptions imply

  • Logistic Regression: How probabilities emerge from linear structures and why it’s suited for classification

  • Decision Trees: Why splitting on feature thresholds can reflect information gain and how shallow vs. deep trees behave differently

  • Support Vector Machines: What margins mean geometrically and why maximizing them tends to improve generalization

Each algorithm is dissected with intuition, geometric interpretation, and guidance on when and why it’s appropriate.


3. Model Interpretation and Behavior

Machine learning isn’t just about predictions — it’s about understanding what models are doing. The book pays special attention to:

  • How model complexity affects performance

  • Bias–variance trade-offs and their impact on generalization

  • Overfitting vs. underfitting, and how to detect and mitigate them

  • Why some features matter more than others in predictions

This deeper interpretive skillset helps you build models you can trust and explain — a key advantage in real-world work.


4. Evaluation Metrics with Insight

Knowing how to train models isn’t enough; you must know how to measure them. The book explains not just what metrics like accuracy or mean squared error are, but why they matter in specific contexts:

  • When to use precision/recall vs. accuracy

  • Why ROC curves help when classes are imbalanced

  • How loss functions shape the learning process

This helps you choose metrics that reflect the real priorities of your problem — not just default ones.


5. Practical Examples and Thought Exercises

To make theory actionable, the book includes examples and thought experiments that show:

  • How models behave with noisy or limited data

  • What happens when assumptions are violated

  • How feature scaling affects distance-based models

  • Why validation and test splits matter for honest evaluation

These insights prepare you to reason about models before you ever implement them.


Who This Book Is For

This book is ideal for:

  • Learners who want deep conceptual understanding, not just formulas

  • Students and professionals preparing for data science roles

  • Developers transitioning into machine learning work

  • Analysts who want to interpret model behavior confidently

  • Anyone curious about how supervised learning actually works

You don’t need advanced math; instead, the focus is on building intuition through reasoning and examples.


Why This Approach Works

Many textbooks teach algorithms as isolated procedures: you follow a recipe, run the code, and hope for good results. But without deep understanding, models can behave unpredictably or mislead you — especially on real messy data.

By starting from first principles — asking why each technique works — this book helps you:

  • Anticipate model behavior before implementation

  • Choose the right algorithm for the right task

  • Understand limitations and pitfalls early

  • Communicate model logic clearly to stakeholders

This isn’t just learning machine learning — it’s mastering machine learning.


Hard Copy: Deep Roots — Book 2: Supervised Machine Learning: Series: Deep Roots: Machine Learning from First Principles (Book 2 of 8) (Deep Roots: Machine Learning ... not just how models work — but why they mu)

Kindle: Deep Roots — Book 2: Supervised Machine Learning: Series: Deep Roots: Machine Learning from First Principles (Book 2 of 8) (Deep Roots: Machine Learning ... not just how models work — but why they mu)

Conclusion

Deep Roots — Book 2: Supervised Machine Learning provides a thoughtful, intuition-driven guide to one of the most important areas of AI and data science. Instead of memorizing models, you’ll learn to reason about them — understanding the mechanics, assumptions, and implications that make supervised learning successful in practice (and where it can fail).

For anyone serious about building reliable, interpretable, and impactful predictive systems, this book offers a clear path from curiosity to comprehension — grounding technical skill in human understanding.

Whether you’re just beginning your machine learning journey or deepening your expertise, this book equips you with both the insights and the confidence to build models that work — and to explain why they work.

Python Coding Challenge - Question with Answer (ID -310126)

 


Explanation:


๐Ÿ”น Import NumPy Library
import numpy as np


This line imports the NumPy library and assigns it the alias np for easy use.

๐Ÿ”น Create Matrix
mat = np.array([[1, 2], [3, 4]])


This line creates a 2×2 NumPy matrix with the given elements.

๐Ÿ”น Initialize Sum Variable
s = 0


This line initializes the variable s to store the sum of diagonal elements.

๐Ÿ”น Loop Through Diagonal Elements
for i in range(len(mat)):


This loop runs through the indices of the matrix rows.

๐Ÿ”น Add Diagonal Elements
s += mat[i][i]


This line accesses and adds each diagonal element of the matrix to s.

๐Ÿ”น Display Result
print(s)


This line prints the final sum of the diagonal elements.

✅ Output
5


๐Ÿ“Š Day 6: Percentage Stacked Bar Chart in Python

 

๐Ÿ”น What is a Percentage Stacked Bar Chart?

A Percentage Stacked Bar Chart displays data where each bar represents 100% of the total, and each segment shows the percentage contribution of a category to that total.
Instead of absolute values, it focuses on proportions.


๐Ÿ”น When Should You Use It?

Use a percentage stacked bar chart when:

  • You want to compare relative contributions

  • Total values differ but composition matters

  • You want to visualize distribution changes over time

  • Absolute numbers are less important than percentage share


๐Ÿ”น Example Scenario

Imagine you are analyzing Product A vs Product B sales over different years.
Even if total sales change each year, this chart helps you understand:

  • Which product dominates each year

  • How the market share shifts over time


๐Ÿ”น Key Idea Behind It

๐Ÿ‘‰ Every bar equals 100%
๐Ÿ‘‰ Data is normalized into percentages
๐Ÿ‘‰ Makes proportional comparison easier and clearer


๐Ÿ”น Python Code (Percentage Stacked Bar Chart)

import matplotlib.pyplot as plt import numpy as np
years = ['2022', '2023', '2024'] product_a = np.array([50, 70, 40]) product_b = np.array([50, 30, 60])
total = product_a + product_b a_percent = product_a / total * 100 b_percent = product_b / total * 100
x = np.arange(len(years)) plt.bar(x, a_percent, label='Product A') plt.bar(x, b_percent, bottom=a_percent, label='Product B') plt.xlabel('Year') plt.ylabel('Percentage')
plt.title('Percentage Stacked Bar Chart') plt.xticks(x, years) plt.legend()
plt.show()

๐Ÿ”น Output Explanation

  • Each bar represents one year

  • The full height of every bar is 100%

  • Blue and orange segments show percentage contribution

  • Easy to compare which product has a higher share each year


๐Ÿ”น Stacked Bar Chart vs Percentage Stacked Bar Chart

FeatureStacked Bar ChartPercentage Stacked Bar Chart
ShowsActual valuesPercentage values
Bar heightVariesAlways 100%
Best forTotal comparisonProportion comparison

๐Ÿ”น Key Takeaways

  • Percentage stacked bar charts focus on relative importance

  • Ideal for composition analysis

  • Helps compare distribution, not magnitude

  • Very useful for market share & survey data


๐Ÿ“Š Day 5: Stacked Bar Chart in Python

 

๐Ÿ“Š Day 5: Stacked Bar Chart in Python 


๐Ÿ” What is a Stacked Bar Chart?

A stacked bar chart displays bars on top of each other instead of side by side.

Each bar represents:

  • The total value of a category

  • The contribution of each sub-category within that total

This makes it easy to see both:
✔ Overall totals
✔ Individual contributions


✅ When Should You Use a Stacked Bar Chart?

Use a stacked bar chart when:

  • You want to show part-to-whole relationships

  • Total value and composition both matter

  • Comparing how components change across categories

Real-world examples:

  • Product-wise sales per year

  • Department-wise expenses

  • Male vs female population by year


๐Ÿ“Š Example Dataset

Let’s visualize yearly sales of two products:

YearProduct AProduct B
20225040
20237060
20249075

Each bar shows total yearly sales, while colors show Product A and Product B contributions.


๐Ÿง  Python Code: Stacked Bar Chart Using Matplotlib

import matplotlib.pyplot as plt import numpy as np years = ['2022', '2023', '2024']
product_a = [50, 70, 90] product_b = [40, 60, 75] x = np.arange(len(years)) plt.bar(x, product_a, label='Product A') plt.bar(x, product_b, bottom=product_a, label='Product B')
plt.xlabel('Year') plt.ylabel('Sales') plt.title('Yearly Sales (Stacked Bar Chart)') plt.xticks(x, years)
plt.legend()

plt.show()

๐Ÿงฉ Code Explanation (Simple)

  • plt.bar(x, product_a) → creates the base bars

  • bottom=product_a → stacks Product B on top of Product A

  • legend() → identifies each product

  • Total bar height = Product A + Product B


๐Ÿ“Š Stacked Bar Chart vs Grouped Bar Chart

Stacked Bar ChartGrouped Bar Chart

Shows composition   Shows comparison
 Highlights totals        Highlights differences
 Parts stacked              Bars side by side

๐Ÿ”‘ Key Takeaways

✔ Best for showing total + breakdown
✔ Useful for composition analysis
✔ Easy to understand trends in parts

๐Ÿ“Š Day 4: Grouped Bar Chart in Python


 ๐Ÿ“Š Day 4: Grouped Bar Chart in Python 

๐Ÿ” What is a Grouped Bar Chart?

A grouped bar chart (also called a clustered bar chart) is used to compare multiple values within the same category.

Instead of one bar per category, you see multiple bars placed side by side for easy comparison.


✅ When Should You Use a Grouped Bar Chart?

Use a grouped bar chart when:

  • You have two or more sub-categories

  • You want to compare values within and across categories

  • Exact comparison between groups is important

Real-world examples:

  • Sales of multiple products across years

  • Marks of boys vs girls in each class

  • Revenue comparison of companies per quarter


๐Ÿ“Š Example Dataset

Let’s compare sales of two products over different years:

YearProduct AProduct B
20225040
20237060
20249075

๐Ÿง  Python Code: Grouped Bar Chart Using Matplotlib

import matplotlib.pyplot as plt import numpy as np # Data years = ['2022', '2023', '2024'] product_a = [50, 70, 90] product_b = [40, 60, 75]
# X positions x = np.arange(len(years)) width = 0.35 # Create grouped bars plt.bar(x - width/2, product_a, width, label='Product A') plt.bar(x + width/2, product_b, width, label='Product B')
# Labels and title plt.xlabel('Year') plt.ylabel('Sales') plt.title('Yearly Sales Comparison') plt.xticks(x, years) plt.legend() # Display chart
plt.show()

๐Ÿงฉ Code Explanation (Simple)

  • np.arange() → creates x-axis positions

  • width → controls bar thickness and spacing

  • x - width/2 & x + width/2 → place bars side by side

  • legend() → explains which bar belongs to which category


๐Ÿ“Š Grouped Bar Chart vs Stacked Bar Chart

Grouped Bar ChartStacked Bar Chart
Bars are side-by-sideBars are stacked
Easy comparisonShows composition
Best for exact valuesBest for proportions

๐Ÿ”‘ Key Takeaways

✔ Used to compare multiple values per category
✔ Bars are placed side by side
✔ Ideal for detailed comparisons

๐Ÿ“Š Day 3: Horizontal Bar Chart in Python

๐Ÿ“Š Day 3: Horizontal Bar Chart in Python


๐Ÿ” What is a Horizontal Bar Chart?

A horizontal bar chart displays bars from left to right instead of bottom to top.

It is especially useful when:

  • Category names are long

  • There are many categories

  • You want to show rankings clearly


✅ When Should You Use a Horizontal Bar Chart?

Use it when:

  • Labels don’t fit well on the x-axis

  • You want easy comparison across categories

  • Displaying Top-N lists

Real-world examples:

  • Most popular programming languages

  • Top-selling products

  • Employee performance ranking


๐Ÿ“Š Example Dataset

Let’s compare popularity of programming languages:

LanguagePopularity
Python95
Java80
JavaScript85
C++70

๐Ÿง  Python Code: Horizontal Bar Chart Using Matplotlib

import matplotlib.pyplot as plt # Data languages = ['Python', 'Java', 'JavaScript', 'C++'] popularity = [95, 80, 85, 70] # Create horizontal bar chart plt.barh(languages, popularity) # Labels and title plt.xlabel('Popularity Score') plt.ylabel('Programming Languages') plt.title('Programming Language Popularity')
# Display chart
plt.show()

๐Ÿงฉ Code Explanation (Simple)

  • plt.barh() → creates a horizontal bar chart

  • Categories appear on the y-axis

  • Values appear on the x-axis

  • Bars grow left to right


๐Ÿ“Š Horizontal Bar vs Vertical Bar Chart

Chart TypeFunction
Vertical Bar (Column Chart)plt.bar()
Horizontal Bar Chartplt.barh()

๐Ÿ”‘ Key Takeaways

✔ Best for long category labels
✔ Improves readability
✔ Ideal for ranking data

Friday, 30 January 2026

Day 43: Mutating Arguments Passed to Functions

 

๐Ÿ Python Mistakes Everyone Makes ❌

Day 43: Mutating Arguments Passed to Functions

This is one of those bugs that looks harmless, works fine in small tests —
and then causes mysterious behavior later in production.


❌ The Mistake

Modifying a mutable argument (like a list or dictionary) inside a function.

def add_item(items):
    items.append("apple") # ❌ mutates the caller's list

my_list = []
add_item(my_list)
print(my_list) # ['apple']

At first glance, this seems fine.
But the function silently changes data it does not own.


❌ Why This Is Dangerous

  • ❌ Side effects are hidden

  • ❌ Makes debugging extremely hard

  • ❌ Breaks assumptions about data immutability

  • ❌ Functions stop being predictable

  • ❌ Reusing the function becomes risky

The caller didn’t explicitly ask for the list to be modified — but it happened anyway.


⚠️ A More Subtle Example

def process(data):
    data["count"] += 1 # ❌ mutates shared state

If data is shared across multiple parts of your app, this change ripples everywhere.


✅ The Correct Way: Avoid Mutation

✔️ Option 1: Work on a copy

def add_item(items):
    new_items = items.copy()
    new_items.append("apple")
    return new_items

my_list = [] 
my_list = add_item(my_list)

Now the function is pure and predictable.


✔️ Option 2: Be explicit about mutation

If mutation is intentional, make it obvious:

def add_item_in_place(items): 
items.append("apple")

Clear naming prevents surprises.


๐Ÿง  Why This Matters

Functions should:

  • Do one thing

  • Have clear contracts

  • Avoid unexpected side effects

Predictable code is maintainable code.


๐Ÿง  Simple Rule to Remember

๐Ÿง  If a function mutates its arguments, make it explicit or avoid it.

When in doubt:

Return new data instead of modifying input.


๐Ÿš€ Final Takeaway

Hidden mutation is one of Python’s most common foot-guns.

Write functions that:

  • Are safe to reuse

  • Don’t surprise callers

  • Make data flow obvious

Your future self (and teammates) will thank you.

Day 42:Not using __slots__ when needed



๐Ÿ Python Mistakes Everyone Makes ❌

Day 42: Not Using __slots__ When Needed

Python classes are flexible by default—but that flexibility comes with a cost. When you create many objects, not using __slots__ can silently waste memory and reduce performance.


❌ The Mistake

Defining classes without __slots__ when you know exactly which attributes the objects will have.

class Point:
   def __init__(self, x, y):
      self.x = x 
        self.y = y

This looks perfectly fine—but every instance gets a __dict__ to store attributes dynamically.


❌ Why This Fails

  • Each object stores attributes in a __dict__

  • Extra memory overhead per instance

  • Slower attribute access

  • Allows accidental creation of new attributes

  • Becomes expensive when creating thousands or millions of objects

This usually goes unnoticed until performance or memory becomes a problem.


✅ The Correct Way

Use __slots__ when:

  • Object structure is fixed

  • You care about memory or speed

  • You’re creating many instances

class Point:
    __slots__ = ("x", "y")

  def __init__(self, x, y):
        self.x = x 
        self.y = y

✅ What __slots__ Gives You

  • ๐Ÿš€ Lower memory usage

  • ⚡ Faster attribute access

  • ๐Ÿ›‘ Prevents accidental attributes

  • ๐Ÿง  Clear object structure

p = Point(1, 2)
p.z = 3 # ❌ AttributeError

This is a feature, not a limitation.


๐Ÿง  When NOT to Use __slots__

  • When objects need dynamic attributes

  • When subclassing extensively (needs extra care)

  • When simplicity matters more than optimization


๐Ÿง  Simple Rule to Remember

๐Ÿ Many objects + fixed attributes → use __slots__
๐Ÿ Few objects or flexible design → skip it


๐Ÿš€ Final Takeaway

__slots__ is not mandatory—but it’s powerful when used correctly.

Use it when:

  • Performance matters

  • Memory matters

  • Object structure is predictable

Write Python that’s not just correct—but efficient too.

Python Coding Challenge - Question with Answer (ID -300126)

 


Explanation:

1️⃣ Variable Initialization
x = 1

A variable x is created.

Its initial value is 1.

This value will be updated repeatedly inside the loop.

2️⃣ Loop Declaration
for i in range(1, 6):

This loop runs with i taking values:

1, 2, 3, 4, 5


The loop will execute 5 times.

3️⃣ Loop Body (Core Logic)
x *= i - x

This line is equivalent to:

x = x * (i - x)


Each iteration:

First computes (i - x)

Then multiplies the current value of x with that result

Stores the new value back into x

4️⃣ Iteration-by-Iteration Execution
๐Ÿ”น Iteration 1 (i = 1)

Current x = 1

Calculation:

x = 1 × (1 − 1) = 0


Updated x = 0

๐Ÿ”น Iteration 2 (i = 2)

Current x = 0

Calculation:

x = 0 × (2 − 0) = 0


Updated x = 0

๐Ÿ”น Iteration 3 (i = 3)

Current x = 0

Calculation:

x = 0 × (3 − 0) = 0


Updated x = 0

๐Ÿ”น Iteration 4 (i = 4)

Current x = 0

Calculation:

x = 0 × (4 − 0) = 0


Updated x = 0

๐Ÿ”น Iteration 5 (i = 5)

Current x = 0

Calculation:

x = 0 × (5 − 0) = 0


Updated x = 0

5️⃣ Final Output
print(x)

After the loop ends, x is still 0.

So the output printed is:

0

APPLICATION OF PYTHON IN FINANCE


Thursday, 29 January 2026

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

 


Code Explanation:

1. Defining the Base Class

class Base:

A class named Base is defined.

This class will be callable because it defines __call__.

2. Defining __call__ in Base
    def __call__(self, x):
        return x + 1


__call__ allows objects of Base (or its subclasses) to be called like a function.

It takes one argument x.

Returns x + 1.

Example:

Base()(3) → 4

3. Defining the Child Class
class Child(Base):

Class Child inherits from Base.

It automatically gains access to Base.__call__.

4. Overriding __call__ in Child
    def __call__(self, x):
        return super().__call__(x) * 2

This method does two things:

Calls the parent class’s __call__ using super():

super().__call__(x)


Multiplies the result by 2.

5. Creating an Object
c = Child()

An instance c of class Child is created.
Since Child defines __call__, c is callable.

6. Calling the Object
print(c(3))

Step-by-step execution:

c(3) calls:

Child.__call__(c, 3)


Inside Child.__call__:

super().__call__(3) → Base.__call__(3) → 3 + 1 = 4

Result is multiplied:

4 * 2 = 8

7. Final Output
8

✅ Final Answer
✔ Output:
8

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

 


Code Explanation:

1. Defining the Class
class Counter:

A class named Counter is defined.

This class will create objects that can be called like functions.

2. Initializing Instance State
    def __init__(self):
        self.n = 0

__init__ is the constructor.

It runs once when an object is created.

An instance variable n is created and initialized to 0.

3. Defining the __call__ Method
    def __call__(self):
        self.n += 1
        return self.n

__call__ makes the object callable.

Each time the object is called:

self.n is increased by 1

The updated value is returned

4. Creating an Object
c = Counter()

An object c of class Counter is created.

self.n is set to 0.

5. First Call: c()
c()

Python internally calls:

c.__call__()


self.n becomes 1

Returns 1

6. Second Call: c()
c()

self.n becomes 2

Returns 2

7. Third Call: c()
c()

self.n becomes 3

Returns 3

8. Printing the Results
print(c(), c(), c())

Prints the return values of the three calls.

9. Final Output
1 2 3

Final Answer
✔ Output:
1 2 3


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


 Code Explanation:

1. Defining the Class
class Action:

A class named Action is defined.

This class will later behave like a function.

2. Defining the __call__ Method
    def __call__(self, x):
        return x * 2

__call__ is a special method in Python.

When an object is called like a function (obj()), Python internally calls:

obj.__call__()


This method takes one argument x and returns x * 2.

3. Creating an Instance
a = Action()

An object a of class Action is created.

Since Action defines __call__, the object becomes callable.

4. Calling the Object Like a Function
print(a(5))


Step-by-step:

Python sees a(5).

It translates this into:

a.__call__(5)


Inside __call__:

x = 5

5 * 2 = 10

The value 10 is returned.

5. Final Output
10

Final Answer
✔ Output:
10

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

 


Code Explanation:

1. Defining the Class
class Cache:

A class named Cache is defined.

2. Defining __getattr__
    def __getattr__(self, name):

__getattr__ is a special method.

It is called only when an attribute is NOT found in:

the instance (self.__dict__)

the class

parent classes

3. Creating the Attribute Dynamically
        self.__dict__[name] = 7

A new attribute is added to the instance dynamically.

The attribute name is whatever was requested (name).

Its value is set to 7.

Example:

c.a = 7

4. Returning the Value
        return 7

The method returns 7.

This value becomes the result of the attribute access.

5. Creating an Object
c = Cache()

An instance c of class Cache is created.

Initially:

c.__dict__ == {}

6. First Access: c.a
c.a

Step-by-step:

Python looks for a in c.__dict__ → not found

Looks in class Cache → not found

Calls __getattr__(self, "a")

Inside __getattr__:

self.__dict__["a"] = 7

Returns 7

Now:

c.__dict__ == {"a": 7}

7. Second Access: c.a
c.a

Step-by-step:

Python looks for a in c.__dict__

Finds a = 7

__getattr__ is NOT called

Value 7 is returned directly

8. Printing the Values
print(c.a, c.a)


First c.a → 7

Second c.a → 7

9. Final Output
7 7

Final Answer
✔ Output:
7 7

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

 


Code Explanation:

1. Class Definition
class Cleaner:

Explanation:

This line defines a class named Cleaner.

2. Method Definition
    def run(self):

Explanation:

run is an instance method of the Cleaner class.

self refers to the current object that calls this method.

3. Deleting the Method from the Class
        del Cleaner.run

Explanation:

This line deletes the run method from the class Cleaner itself.

After this executes:

The method run no longer exists in the Cleaner class.

This affects all instances of Cleaner, not just the current one.

Important:

The method is deleted while it is executing.

Python allows this because the function object is already being used.

4. Returning a Value
        return "done"

Explanation:

Even though Cleaner.run has been deleted,

The current call continues normally and returns "done".

5. Creating an Object
c = Cleaner()

Explanation:

Creates an instance of the Cleaner class.

The object c can initially access run through the class.

6. Calling the Method
print(c.run())

Explanation:

c.run() calls the method:

Python finds run in Cleaner.

Method execution starts.

Cleaner.run is deleted during execution.

"done" is returned.

Output:
done

7. Checking If Method Still Exists
print(hasattr(Cleaner, "run"))

Explanation:

hasattr(Cleaner, "run") checks whether the class Cleaner
still has an attribute named run.

Since del Cleaner.run was executed earlier:

The method no longer exists in the class.

Output:
False

8. Final Summary 
Methods belong to the class, not the object.

A method can be deleted from the class while it is running.

Deleting a class method affects all instances.

The current method call still completes successfully.

Final Output of the Program
done

4 Machine Learning Books You Can Read for FREE (Legally)

 



1. The Kaggle Book: Master Data Science Competitions with Machine Learning, GenAI, and LLMs

This book is a hands-on guide for anyone who wants to excel in Kaggle competitions and real-world machine learning projects.

Covers:

  • End-to-end Kaggle competition workflows

  • Feature engineering & model selection

  • Advanced machine learning techniques

  • Generative AI & Large Language Models (LLMs)

  • Practical tips from Kaggle Grandmasters

๐Ÿ‘‰ Perfect for intermediate to advanced data science learners who want to sharpen their competitive ML skills and apply cutting-edge AI techniques. ๐Ÿš€


2. Learning Theory from First Principles

This book builds a deep, mathematical understanding of machine learning by developing learning theory from the ground up.

Covers:

  • Foundations of statistical learning theory

  • PAC learning and generalization theory

  • VC dimension and capacity control

  • Convexity, optimization, and regularization

  • Rigorous proofs with clear intuition

๐Ÿ‘‰ Perfect for advanced students, researchers, and practitioners who want to truly understand why machine learning algorithms work—not just how to use them. ๐Ÿ“˜๐Ÿง 


3.AI and Machine Learning Unpacked: A Practical Guide for Decision Makers in Life Sciences and Healthcare

This book demystifies AI and machine learning for leaders and decision-makers in life sciences and healthcare, focusing on real-world impact rather than algorithms.

Covers:

  • Core AI & ML concepts explained in plain language

  • Use cases in healthcare, pharma, and life sciences

  • Data strategy, governance, and regulatory considerations

  • Evaluating AI solutions and vendors

  • Translating AI insights into business and clinical value

๐Ÿ‘‰ Perfect for executives, managers, clinicians, and non-technical professionals who need to make informed AI decisions without diving deep into code or math. ๐Ÿฅ๐Ÿค–


4.  Python for Probability and Statistics in Machine Learning

This book bridges the gap between mathematical theory and practical implementation, showing how probability and statistics power modern machine learning—using Python throughout.

Covers:

  • Core probability concepts (random variables, distributions, Bayes’ theorem)

  • Descriptive & inferential statistics

  • Hypothesis testing and confidence intervals

  • Statistical modeling for machine learning

  • Hands-on implementations with Python

๐Ÿ‘‰ Perfect for ML learners, data scientists, and AI practitioners who want to strengthen their statistical foundations and build more reliable, data-driven machine learning models. ๐Ÿ“Š๐Ÿ

Wednesday, 28 January 2026

Day 35: Assuming __del__ Runs Immediately

 

๐Ÿ Python Mistakes Everyone Makes ❌

Day 35: Assuming __del__ Runs Immediately

Python’s __del__ method looks like a destructor, so it’s easy to assume it behaves like one in languages such as C++ or Java.
But this assumption can lead to unpredictable bugs and resource leaks.


❌ The Mistake

Relying on __del__ to clean up resources immediately when an object is “deleted”.

class Demo:
    def __del__(self):
        print("Object deleted")

obj = Demo()
obj = None # ❌ assuming __del__ runs here

You might expect "Object deleted" to print right away — but that is not guaranteed.


❌ Why This Fails

  • __del__ is called only when an object is garbage collected

  • Garbage collection timing is not guaranteed

  • Other references to the object may still exist

  • Circular references can delay or prevent __del__

  • Behavior can vary across Python implementations (CPython, PyPy, etc.)

In short:
๐Ÿ‘‰ Deleting a reference ≠ deleting the object


⚠️ Real-World Problems This Causes

  • Files left open

  • Database connections not closed

  • Network sockets hanging

  • Memory leaks

  • Inconsistent behavior across environments

These bugs are often hard to detect and harder to debug.


✅ The Correct Way

Always clean up resources explicitly.

class Resource:
   def close(self):
     print("Resource released")

r = Resource()
try:
   print("Using resource")
finally:
 r.close() # ✅ guaranteed cleanup

This ensures cleanup no matter what happens.


๐Ÿง  Even Better: Use with

When possible, use context managers:

with open("data.txt") as f:
   data = f.read()
# file is safely closed here

Python guarantees cleanup when exiting the with block.


๐Ÿšซ Why __del__ Is Dangerous for Cleanup

  • Order of destruction is unpredictable

  • May never run before program exits

  • Errors inside __del__ are ignored

  • Makes code fragile and hard to reason about

__del__ is for last-resort cleanup, not critical resource management.


๐Ÿง  Simple Rule to Remember

๐Ÿ Never rely on __del__ for important cleanup
๐Ÿ Use with or explicit cleanup methods instead


๐Ÿš€ Final Takeaway

If a resource must be released, don’t wait for Python to decide when.

Be explicit.
Be predictable.
Write safer Python.


Popular Posts

Categories

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

Followers

Python Coding for Kids ( Free Demo for Everyone)