Tuesday, 10 March 2026

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

 


1️⃣ List Creation

x = [1,2,3]

This creates a list named x containing three elements:

[1, 2, 3]

2️⃣ List Slicing

x[::-1]

This uses Python slicing syntax:

list[start : stop : step]

Here:

start = default (beginning)
stop = default (end)
step = -1

A step of -1 means move backward through the list.

So Python reads the list from end to start.


3️⃣ Reversing the List

Original list:

[1, 2, 3]

Reading backward:

[3, 2, 1]

4️⃣ Print Statement

print(x[::-1])

This prints the reversed list.

✅ Final Output

[3, 2, 1]

🔥 Important Point

[::-1] is a Python shortcut to reverse a list, string, or tuple.

Example:

text = "python"
print(text[::-1])

Output:

Monday, 9 March 2026

Day 49: Strip Plot in Python 📊

 

Day 49: Strip Plot in Python 📊

A Strip Plot is a simple yet powerful visualization used to display individual data points across categories. It is especially useful when you want to see the distribution of values while keeping every observation visible.

Unlike aggregated charts like bar plots or box plots, a strip plot shows each data point, making it easier to understand how values are spread within a category.

In this example, we visualize daily spending patterns using the Tips dataset.


📊 What is a Strip Plot?

A Strip Plot is a categorical scatter plot where:

  • One axis represents categories

  • The other axis represents numeric values

  • Each dot represents one observation

To avoid overlapping points, the plot can use jitter, which slightly spreads points horizontally.

This helps reveal patterns that would otherwise be hidden if the points stacked directly on top of each other.


📁 Dataset Used

This example uses the Tips dataset from Seaborn, which contains information about restaurant bills and tips.

Some important columns in the dataset include:

  • total_bill → Total amount spent

  • tip → Tip given

  • day → Day of the week

  • time → Lunch or dinner

In this visualization, we focus on:

  • Day of the week

  • Total bill amount


💻 Python Code

import seaborn as sns
import matplotlib.pyplot as plt

sns.set_theme(style="white", font='serif')
plt.figure(figsize=(10, 6), facecolor='#FAF9F6')

df = sns.load_dataset("tips")

ax = sns.stripplot(
x="day",
y="total_bill",
data=df,
jitter=0.25,
size=8,
alpha=0.6,
palette=["#E5989B", "#B5838D", "#6D6875", "#DBC1AD"]
)

ax.set_facecolor("#FAF9F6")
sns.despine(left=True, bottom=True)

plt.title("Daily Spending Flow", fontsize=18, pad=20, color='#4A4A4A')
plt.xlabel("")
plt.ylabel("Amount ($)", fontsize=12, color='#6D6875')

plt.show()

🔎 Code Explanation

1️⃣ Import Libraries

We import the required libraries:

  • Seaborn → for statistical data visualization

  • Matplotlib → for plotting and customization


2️⃣ Set the Visual Style

sns.set_theme(style="white", font='serif')

This gives the plot a clean editorial-style appearance with a serif font.


3️⃣ Load the Dataset

df = sns.load_dataset("tips")

This loads the built-in tips dataset from Seaborn.


4️⃣ Create the Strip Plot

sns.stripplot(x="day", y="total_bill", data=df, jitter=0.25)

Here:

  • x-axis → Day of the week

  • y-axis → Total bill amount

  • jitter spreads points slightly to avoid overlap

Each point represents one customer's bill.


5️⃣ Improve Visual Appearance

The code also customizes:

  • Background color

  • Color palette

  • Title and labels

  • Removed extra axis lines using sns.despine()

This creates a clean, modern-looking chart.


📈 Insights from the Plot

From the visualization we can observe:

  • Saturday and Sunday have more data points, meaning more restaurant visits.

  • Bills on weekends tend to be higher compared to weekdays.

  • Thursday and Friday have fewer observations and generally lower spending.

This helps quickly identify spending patterns across days.


🚀 When Should You Use a Strip Plot?

Strip plots are useful when you want to:

  • Show individual observations

  • Visualize data distribution across categories

  • Explore patterns in small to medium datasets

  • Perform exploratory data analysis

They are often used in data science, statistics, and exploratory analysis.


🎯 Conclusion

A Strip Plot is one of the simplest ways to visualize categorical distributions while keeping every data point visible. By adding jitter, it prevents overlap and clearly shows how values are distributed within each category.

Using Seaborn in Python, creating a strip plot becomes easy and visually appealing. In this example, we explored daily spending patterns and discovered clear differences between weekday and weekend restaurant bills.

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

 


Code Explanation:

1. Defining Class D
class D:

Explanation:

This line defines a class named D.

This class will act as a descriptor.

A descriptor is a class that defines methods like __get__, __set__, or __delete__ to control attribute access.

2. Defining __get__ Method
def __get__(self, obj, objtype):

Explanation:

__get__ is a descriptor method.

It is automatically called when the attribute is accessed (read).

Parameters:

self → the descriptor object (D)

obj → the instance of class A

objtype → the class A

Example call when a.x is accessed:

D.__get__(descriptor, a, A)

3. Returning the Value
return obj._x

Explanation:

This returns the value stored in the instance variable _x.

The descriptor redirects access to _x inside the object.

So:

a.x → returns a._x

4. Defining __set__ Method
def __set__(self, obj, value):

Explanation:

__set__ is another descriptor method.

It is automatically called when the attribute is assigned a value.

Example when writing:

a.x = 5

Python internally calls:

D.__set__(descriptor, a, 5)

Parameters:

self → descriptor object

obj → instance of A

value → value being assigned

5. Modifying the Value Before Storing
obj._x = value * 2

Explanation:

Instead of storing the value directly, it multiplies the value by 2.

Then it stores it in obj._x.

So when:

a.x = 5

It becomes:

a._x = 10

6. Defining Class A
class A:

Explanation:

This creates another class named A.

7. Creating Descriptor Attribute
x = D()

Explanation:

Here an object of class D is assigned to attribute x.

This makes x a descriptor attribute.

Any access to x will trigger __get__ or __set__.

So:

A.x → descriptor object of class D

8. Creating an Object
a = A()

Explanation:

This creates an instance a of class A.

9. Assigning Value to x
a.x = 5

Explanation:

Since x is a descriptor, Python calls:

D.__set__(descriptor, a, 5)

Inside __set__:

obj._x = value * 2

So:

a._x = 5 * 2
a._x = 10

10. Accessing x
print(a.x)

Explanation:

Python calls:

D.__get__(descriptor, a, A)

Inside __get__:

return obj._x

Since:

a._x = 10

It returns 10.

11. Final Output
10

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

 


Code Explanation:

1. Defining Class A

class A:

Explanation:

This line defines a class named A.

A class is a template used to create objects.

2. Defining __getattribute__ Method

def __getattribute__(self, name):

Explanation:

__getattribute__ is a special (magic) method in Python.

It is automatically called every time any attribute of an object is accessed.

self → the current object

name → the attribute name being accessed.

Example:

When we write a.x, Python internally calls:

a.__getattribute__("x")

3. Checking if Attribute Name is "x"

if name == "x":

    return 10

Explanation:

If the attribute being accessed is x, the method returns 10.

This means any access to a.x will return 10, even if x is not defined.

So:

a.x → 10

4. Accessing Default Attribute Behavior

return super().__getattribute__(name)

Explanation:

If the attribute is not "x", Python calls the parent class implementation of __getattribute__.

super() refers to the base object behavior.

This line tells Python to look for the attribute normally.

If the attribute exists → return it.

If it does not exist → Python will trigger __getattr__.

5. Defining __getattr__

def __getattr__(self, name):

    return 20

Explanation:

__getattr__ is another special method.

It is called only when the attribute is not found normally.

It returns 20 for any missing attribute.

So if an attribute does not exist, Python returns:

20

6. Creating an Object

a = A()

Explanation:

This creates an object a of class A.

7. Printing Attributes

print(a.x, a.y)

Python evaluates this in two parts.

7.1 Accessing a.x

Python calls:

a.__getattribute__("x")

Inside __getattribute__:

name == "x" → True

Returns 10

So:

a.x → 10

7.2 Accessing a.y

Python calls:

a.__getattribute__("y")

Inside __getattribute__:

name == "x" → False

Calls:

super().__getattribute__("y")

But y does not exist in the object.

So Python calls:

__getattr__("y")

This returns:

20

So:

a.y → 20

8. Final Output

10 20


900 Days Python Coding Challenges with Explanation

Day 48: Beeswarm Plot in Python 🐝📊

 

A Beeswarm Plot (also called a Swarm Plot) is a powerful visualization used to display the distribution of data points across different categories. Unlike a simple scatter plot, a beeswarm plot adjusts the position of points so they don’t overlap, making it easier to see how data is spread within each category.

In this example, we use the Iris dataset to visualize how petal length varies across different flower species.


🔹 Why Use a Beeswarm Plot?

Beeswarm plots are useful when you want to:

  • Show individual data points

  • Understand the distribution of values

  • Compare multiple categories

  • Avoid overlapping points like in regular scatter plots

They are commonly used in data analysis, exploratory data science, and statistical visualization.


📊 Dataset Used

We are using the Iris dataset, one of the most popular datasets in machine learning and statistics.

The dataset contains measurements of iris flowers including:

  • Sepal Length

  • Sepal Width

  • Petal Length

  • Petal Width

  • Species

The three species are:

  • Setosa

  • Versicolor

  • Virginica

In this visualization, we compare petal length across these species.


🧠 Python Code

import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
import pandas as pd

# Load dataset
iris = load_iris()

# Create dataframe
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df["Species"] = iris.target_names[iris.target]

# Create Beeswarm Plot
plt.figure(figsize=(8,5))
sns.swarmplot(data=df, x="Species", y="petal length (cm)")

# Title
plt.title("Beeswarm Plot: Petal Length by Species")

plt.tight_layout()
plt.show()

🔍 Code Explanation

1️⃣ Import Libraries

We import the required libraries:

  • Seaborn → for statistical visualizations

  • Matplotlib → for plotting

  • Scikit-learn → to load the Iris dataset

  • Pandas → for data manipulation


2️⃣ Load the Dataset

iris = load_iris()

This loads the iris dataset from scikit-learn.


3️⃣ Create a DataFrame

df = pd.DataFrame(iris.data, columns=iris.feature_names)

We convert the dataset into a pandas DataFrame for easier handling.

Then we add the species column:

df["Species"] = iris.target_names[iris.target]

4️⃣ Create the Beeswarm Plot

sns.swarmplot(data=df, x="Species", y="petal length (cm)")

This line creates the beeswarm plot where:

  • x-axis → flower species

  • y-axis → petal length

  • Each dot represents one observation

The swarm algorithm spreads points horizontally to avoid overlap.


5️⃣ Add Title and Display

plt.title("Beeswarm Plot: Petal Length by Species")
plt.show()

This adds a chart title and displays the plot.


📈 What Insights Can We See?

From the beeswarm plot:

  • Setosa flowers have small petal lengths

  • Versicolor has medium petal lengths

  • Virginica generally has larger petals

The plot clearly shows distinct clusters for each species, which is why the Iris dataset is often used for classification problems in machine learning.


🚀 When Should You Use Beeswarm Plots?

Use beeswarm plots when you want to:

  • Show raw data points

  • Compare distributions across categories

  • Avoid overlapping points

  • Perform exploratory data analysis

They are especially useful in data science, biology, statistics, and machine learning.


🎯 Conclusion

The Beeswarm Plot is a simple yet powerful way to visualize categorical data distributions while preserving individual data points. Using Seaborn in Python, creating this plot becomes quick and effective for exploring patterns within your dataset.

In just a few lines of code, we were able to visualize petal length differences across iris species, revealing clear distinctions between the groups.

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

 


1️⃣ range(3)

range(3) generates numbers starting from 0 up to 2.

So the values will be:

0, 1, 2

2️⃣ for Loop Execution

The loop runs three times.

Iteration steps:

IterationValue of iOutput
100
211
322

So the loop prints:

0
1
2

3️⃣ else with for Loop

In Python, a for loop can have an else block.

The else block executes only if the loop finishes normally (no break statement).

Since there is no break in this loop, the else block runs.


4️⃣ Final Output

0
1
2
Done

⚡ Important Concept

If we add break, the else will not run.

Example:

for i in range(3):
print(i)
break
else:
print("Done")

Output:

0

Done will not print because the loop stopped using break.

AUTOMATING EXCEL WITH PYTHON

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

 


Code Explanation:

1. Defining Class A
class A:

Explanation:

This line creates a class named A.

A class is a blueprint for creating objects.

2. Defining Method f
def f(self):
    return "A"

Explanation:

A method f is defined inside class A.

self refers to the current object (instance) of the class.

The method returns the string "A" when called.

So the class now contains a method:

A.f() → returns "A"

3. Creating an Object
a = A()

Explanation:

This creates an object a of class A.

Now a can access the class methods and attributes.

Example:

a.f()  → "A"

4. Assigning a New Attribute to the Object
a.f = "value"

Explanation:

Here we assign "value" to a.f.

This creates an instance attribute f inside object a.

In Python, instance attributes override class attributes or methods with the same name.

So now:

a.f → "value"

The original method f in class A is shadowed (hidden) by the instance variable.

5. Printing the Value
print(a.f)

Explanation:

Python first looks for attribute f inside the object a.

It finds a.f = "value".

Therefore it prints "value", not the method.

6. Final Output
value

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

 


Code Explanation:

1. Defining Class A
class A:
    data = []

Explanation:

class A: creates a class named A.

Inside the class, a variable data is defined.

data = [] creates an empty list.

This list is a class variable, not an instance variable.

A class variable is shared by the class and all its subclasses and objects unless overridden.

So currently:

A.data → []

2. Creating Subclass B
class B(A):
    pass

Explanation:

class B(A): means B inherits from A.

pass means the class has no additional code.

Since B inherits from A, it also has access to A.data.

So:

B.data → refers to A.data

3. Creating Subclass C
class C(A):
    pass

Explanation:

class C(A): means C also inherits from A.

pass means nothing new is added.

C also inherits the class variable data from A.

So:

C.data → refers to A.data

4. Modifying the List Through B
B.data.append(10)

Explanation:

B.data refers to A.data because B inherited it.

.append(10) adds 10 to the list.

Since the list is shared, the change affects A.data and C.data as well.

Now the list becomes:

A.data → [10]
B.data → [10]
C.data → [10]

5. Printing the Values
print(A.data, C.data)

Explanation:

A.data prints the class variable of A.

C.data also refers to the same list inherited from A.

Since the list was modified earlier, both show the same value.

Final Output
[10] [10]

Saturday, 7 March 2026

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

 




Explanation:

1. Creating a List
nums = [1, 2, 3]

Explanation:

nums is a variable name.

[1, 2, 3] is a list in Python.

The list contains three integer elements: 1, 2, and 3.

This line stores the list inside the variable nums.

After execution:

nums → [1, 2, 3]

2. Applying the map() Function
result = map(lambda x: x+1, nums)

Explanation:

map() is a built-in Python function.

It is used to apply a function to every element of an iterable (like a list).

map() takes two arguments:

A function

An iterable (list, tuple, etc.)

In this line:

The function is lambda x: x+1

The iterable is nums

So map() will apply the function to each element in the list [1,2,3].

The result is stored in the variable result.

⚠️ Important:
map() returns a map object (iterator), not a list.

Example internal processing:

Element Operation Result
1 1 + 1 2
2 2 + 1 3
3 3 + 1 4

But these values are not shown yet because they are inside the map object.

3. Understanding the Lambda Function

Inside the map() function:

lambda x: x + 1

Explanation:

lambda is used to create a small anonymous function (function without a name).

x is the input value.

x + 1 means add 1 to the input value.

Example:

x x+1
1 2
2 3
3 4

4. Printing the Result
print(result)

Explanation:

This prints the map object, not the actual mapped values.

Because result is an iterator, Python shows its memory reference.

Output example:

<map object at 0x00000211B4D5C070>

Python for Cybersecurity

📊 Day 47: Mosaic Plot in Python

 

 Day 47: Mosaic Plot in Python

On Day 47 of our Data Visualization series, we explored a powerful chart for analyzing relationships between categorical variables — the Mosaic Plot.

When you want to understand how two (or more) categorical variables interact with each other, Mosaic Plots provide a clear and intuitive visual representation.

Today, we applied it to the classic Iris dataset to examine the relationship between Species and Petal Size category.


🎯 What is a Mosaic Plot?

A Mosaic Plot is a graphical method for visualizing contingency tables (cross-tabulated categorical data).

It represents:

  • Categories as rectangles

  • Width proportional to one variable

  • Height proportional to another variable

  • Area representing frequency or proportion

👉 The larger the rectangle, the higher the frequency of that category combination.


📊 Dataset Used: Iris Dataset

The Iris dataset contains:

  • Sepal Length

  • Sepal Width

  • Petal Length

  • Petal Width

  • Species (Setosa, Versicolor, Virginica)

For this visualization, we:

  1. Used Species as one categorical variable

  2. Converted Petal Length into 3 categories:

    • Small

    • Medium

    • Large

This helps us visually compare petal size distribution across species.


🧑‍💻 Python Implementation


✅ Step 1: Import Libraries

import pandas as pd
import matplotlib.pyplot as plt
from statsmodels.graphics.mosaicplot import mosaic
from sklearn.datasets import load_iris
  • Pandas → Data manipulation

  • Matplotlib → Plot rendering

  • Statsmodels → Mosaic plot function

  • Scikit-learn → Dataset loading


✅ Step 2: Load and Prepare Data

iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df["Species"] = iris.target_names[iris.target]

We convert numeric species labels into readable category names.


✅ Step 3: Create Petal Size Categories

df["Petal Size"] = pd.cut(
df["petal length (cm)"],
3,
labels=["Small", "Medium", "Large"]
)

Here we divide petal length into three equal bins.

This transforms a continuous variable into a categorical one.


✅ Step 4: Create the Mosaic Plot

plt.figure(figsize=(9, 5))
mosaic(df, ["Species", "Petal Size"], gap=0.02)
plt.title("Mosaic Plot: Species vs Petal Size")
plt.tight_layout()
plt.show()

Key Parameters:

  • ["Species", "Petal Size"] → Defines categorical relationship

  • gap=0.02 → Adds spacing between tiles

  • figsize → Controls plot size


📈 What the Visualization Reveals

From the Mosaic Plot:

🌸 Setosa

  • Almost entirely in the Small petal category

  • Very little variation

🌿 Versicolor

  • Mostly in the Medium category

  • Some overlap into Small and Large

🌺 Virginica

  • Dominantly in the Large category

  • Some presence in Medium


🔍 Key Insight

The Mosaic Plot clearly shows that:

  • Petal size is strongly associated with species

  • Species are well separated based on petal length

  • This confirms why petal measurements are highly important features in classification models

Even without machine learning, we can visually detect separation patterns.


💡 Why Use Mosaic Plots?

✔ Excellent for categorical comparisons
✔ Shows proportional relationships clearly
✔ Works well with contingency tables
✔ Helpful in statistical analysis
✔ Easy to interpret once understood


🚀 Real-World Applications

  • Marketing: Customer segment vs product category

  • Healthcare: Disease type vs severity level

  • Education: Grade vs performance category

  • Business: Region vs sales category

  • Survey Analysis


📌 Day 47 Takeaway

Mosaic Plots transform categorical relationships into visual area comparisons.

They help you:

  • Understand category dominance

  • Identify imbalances

  • Discover associations

  • Validate statistical assumptions

Popular Posts

Categories

100 Python Programs for Beginner (119) AI (215) Android (25) AngularJS (1) Api (7) Assembly Language (2) aws (28) Azure (9) BI (10) Books (262) Bootcamp (1) C (78) C# (12) C++ (83) Course (86) Coursera (300) Cybersecurity (29) data (4) Data Analysis (27) Data Analytics (20) data management (15) Data Science (318) Data Strucures (16) Deep Learning (130) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (19) Finance (10) flask (3) flutter (1) FPL (17) Generative AI (65) Git (10) Google (50) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (41) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (258) Meta (24) MICHIGAN (5) microsoft (11) Nvidia (8) Pandas (13) PHP (20) Projects (32) Python (1263) Python Coding Challenge (1068) Python Mistakes (50) Python Quiz (439) 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)