Saturday, 22 February 2025

Sandglass Pattern plot using python

 

import numpy as np

import matplotlib.pyplot as plt

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

y_upper = 1 - abs(x)  

y_lower = abs(x) - 1  

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

ax.fill_between(x, y_upper, 1, color="royalblue", alpha=0.7)  

ax.fill_between(x, y_lower, -1, color="tomato", alpha=0.7)  

ax.set_xlim(-1.2, 1.2)

ax.set_ylim(-1.2, 1.2)

ax.set_xticks([])

ax.set_yticks([])

ax.set_frame_on(False)

ax.axhline(0, color="black", linewidth=1.2, linestyle="--") 

plt.title("Hourglass Pattern Plot")

plt.show()

#source code --> clcoding.com 


Code Explanation:

Import Necessary Libraries

import numpy as np

import matplotlib.pyplot as plt

numpy is used for numerical operations, such as generating x values.

matplotlib.pyplot is used for visualization.


Define X-Coordinates for the Plot

x = np.linspace(-1, 1, 200)

np.linspace(-1, 1, 200):

Generates 200 evenly spaced values between -1 and 1 for smooth curves.

These values are used for defining the sandglass shape.


Define Y-Coordinates for the Upper and Lower Parts

y_upper = 1 - np.abs(x)  # Top inverted triangle

y_lower = np.abs(x) - 1  # Bottom triangle

y_upper = 1 - np.abs(x):

Defines an inverted triangle (top part of the sandglass).

As x moves from -1 to 1, y_upper decreases from 1 to 0.

y_lower = np.abs(x) - 1:

Defines a regular triangle (bottom part of the sandglass).

As x moves from -1 to 1, y_lower increases from -1 to 0.

Together, they form a symmetrical sandglass shape!


Create the Figure and Set Background

fig, ax = plt.subplots(figsize=(6, 8), facecolor="black")

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

Creates a taller figure (6x8) to emphasize the sandglass shape.

facecolor="black":

Sets the background color to black for better contrast.


Apply a Gradient Effect for Depth

for i in range(8):

    alpha = (8 - i) / 8  # Fading effect

    scale = 1 - i * 0.1  # Shrinking effect for layers

    ax.fill_between(x * scale, y_upper * scale, 1 * scale, color="deepskyblue", alpha=alpha)

    ax.fill_between(x * scale, y_lower * scale, -1 * scale, color="orangered", alpha=alpha)

A loop is used to create multiple layers to simulate a gradient depth effect.

alpha = (8 - i) / 8:

Decreases transparency from 1 to 0.1 as layers go deeper.

scale = 1 - i * 0.1:u

Shrinks each layer slightly to create a depth illusion.

fill_between() is used to fill the upper (blue) and lower (red) triangles.

This creates a smooth, glass-like fading effect, making the sandglass look more 3D.


Add a Dashed Symmetry Line

ax.axhline(0, color="white", linestyle="--", linewidth=1.2, alpha=0.6)

axhline(0): Draws a horizontal dashed line at y = 0.

This emphasizes symmetry and gives a structured appearance.


Remove Axis Details for a Clean Look

ax.set_xlim(-1.2, 1.2)

ax.set_ylim(-1.2, 1.2)

ax.set_xticks([])

ax.set_yticks([])

ax.set_frame_on(False)

set_xlim(-1.2, 1.2) / set_ylim(-1.2, 1.2):

Expands axes slightly for better visibility.

set_xticks([]) / set_yticks([]):

Removes axis labels to make the plot cleaner.

set_frame_on(False):

Removes the frame/border for a sleek look.


Add a Title and Show the Plot

ax.set_title("Sandglass Pattern Plot ", fontsize=14, fontweight="bold", color="white", pad=15)

plt.show()

Adds a bold, centered title with white color.

plt.show(): Displays the final sandglass plot.


Python Coding Challange - Question With Answer(01220225)

 


Code Analysis and Explanation


queue = {'name', 'age', 'DOB'}
print(queue)

1. Understanding the Code

  • queue is assigned a set containing three string elements: 'name', 'age', and 'DOB'.
  • The print(queue) statement displays the contents of the set.

2. Key Properties of Sets in Python

a) Sets are Unordered

  • Unlike lists ([]) or tuples (()), sets {} do not maintain a fixed order for their elements.
  • When printing, Python determines the order dynamically, so the output may vary each time you run the code.

b) Sets Contain Unique Elements

  • If duplicate values were added to the set, Python would automatically remove them because sets store only unique values.

c) Sets are Mutable

  • You can add or remove elements from a set using .add() and .remove().

3. Possible Outputs

Since sets do not maintain order, the printed output could be any of the following:


{'name', 'age', 'DOB'}
{'age', 'DOB', 'name'} {'DOB', 'name', 'age'}
{'DOB', 'age', 'name'}
  • The elements will always be present, but their order is not guaranteed.

4. Why is the Order Different Each Time?

  • Sets are implemented as hash tables in Python.
  • Hashing ensures fast lookups but does not maintain order.

5. What If You Want a Fixed Order?

If you want to maintain order, consider:

  1. Using a List ([])

    queue = ['name', 'age', 'DOB']
    print(queue) # Always prints: ['name', 'age', 'DOB']
  2. Sorting the Set Before Printing


    print(sorted(queue)) # Prints: ['DOB', 'age', 'name']

6. Example Set Operations


queue.add('gender') # Add an element
queue.remove('age') # Remove an element
print(queue) # Output may vary

7. Summary

Sets are unordered → Elements may print in a different order.
Sets contain unique elements → Duplicates are automatically removed.
Use lists if order matters → Lists maintain insertion order.

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

 


Explanation:

1. Understanding partial from functools

The partial function is used to fix some arguments of a function, creating a new function with fewer parameters.

2. Defining the Function add

def add(x, y, z):

    return x + y + z

This function takes three parameters (x, y, and z) and returns their sum.

3. Using partial to Create add_five

add_five = partial(add, 5)

Here, partial(add, 5) creates a new function add_five where the first argument (x) is pre-filled with 5.

add_five(y, z) is now equivalent to calling add(5, y, z).

4. Calling add_five(3, 2)

print(add_five(3, 2))

Since add_five is partial(add, 5), calling add_five(3, 2) is the same as calling:

add(5, 3, 2)

5 + 3 + 2 = 10, so the output is:


Output:

10

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

 


Explanation:

Class A Definition:

A is a class that has a method show() which returns the string "A".

Class B Definition:

B is a subclass of A (class B(A):), meaning B inherits everything from A.

The keyword pass is used, which means B does not introduce any new attributes or methods—it simply inherits from A.

Creating an Instance of B:

B() creates an object of class B.

Calling show() on an Instance of B:

print(B().show()):

Since B does not have its own show() method, it looks up the method in its parent class (A).

The show() method of A is executed, returning "A".

Output:

A

Friday, 21 February 2025

Spiral Pattern plot using python



 import matplotlib.pyplot as plt

import numpy as np

theta=np.linspace(0,4*np.pi,500)

r=np.linspace(0,10,500)

x=r*np.cos(theta)

y=r*np.sin(theta)

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

plt.plot(x,y,color='blue',linewidth=2)

plt.title("Spiral pattern plot")

plt.axis("equal")

plt.show()

#source code --> clcoding.com

Code Explanation:

1. Import Necessary Libraries

import numpy as np

import matplotlib.pyplot as plt

numpy is used for numerical operations, like creating arrays.

matplotlib.pyplot is used for plotting graphs.


2. Define the Spiral Parameters

theta = np.linspace(0, 4 * np.pi, 500)  # Angle values

r = np.linspace(0, 10, 500)  # Radius values

theta represents the angle in radians, ranging from 0 to 4π (two full turns).

r represents the radius, increasing from 0 to 10.

np.linspace(start, stop, num_points) creates 500 evenly spaced values.


3. Convert to Cartesian Coordinates

x = r * np.cos(theta)

y = r * np.sin(theta)

The spiral is defined in polar coordinates (r, θ), but Matplotlib uses Cartesian coordinates (x, y).


4. Plot the Spiral

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

plt.plot(x, y, color='blue', linewidth=2)

plt.title("Spiral Pattern")

plt.axis("equal")  # Keep aspect ratio equal

plt.show()

plt.figure(figsize=(6,6)): Creates a square figure (6x6 inches).

plt.plot(x, y, color='blue', linewidth=2): Plots the spiral in blue with a thicker line.

plt.title("Spiral Pattern"): Adds a title to the plot.

plt.axis("equal"): Ensures equal scaling on both axes to maintain the circular shape.

plt.show(): Displays the plot.


Zig Zag pattern plot using python

 


import numpy as np

import matplotlib.pyplot as plt

size=10

x=np.arange(size)

y=np.where(x%2==0,1,0)

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

plt.plot(x,y,marker='o',linestyle='-',color='orange',markersize=8,linewidth=2)


ax.set_xlim(-1,size)

ax.set_ylim(-0.5,1.5)

ax.set_xticks([])

ax.set_yticks([])

ax.set_frame_on(False)

plt.title('Zig zag pattern plot')

plt.show()

#source code --> clcoding.com 

Code Explanation:

1. Import Required Libraries
import numpy as np
import matplotlib.pyplot as plt
numpy is used to generate numerical arrays.
matplotlib.pyplot is used to create and display the zigzag plot.

2. Define the Number of Zigzag Points
size = 10  # Change this for more or fewer zigzags
The variable size determines the number of points in the zigzag pattern.
Increasing this value makes the zigzag longer.

3. Create X and Y Coordinates
x = np.arange(size)  # X coordinates (0,1,2,...)
y = np.where(x % 2 == 0, 1, 0)  # Alternate Y values (1, 0, 1, 0, ...)
x = np.arange(size) generates an array [0, 1, 2, ..., size-1], representing evenly spaced x-coordinates.
y = np.where(x % 2 == 0, 1, 0) assigns alternating y values:
If x is even, y = 1 (peak).
If x is odd, y = 0 (valley).
This creates the zigzag effect.
Example of x and y values for size = 10:
x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
y = [1, 0, 1, 0, 1, 0, 1, 0, 1, 0]

4. Create the Figure and Axis
fig, ax = plt.subplots(figsize=(6, 4))
plt.subplots() creates a figure (fig) and an axis (ax).
figsize=(6,4) makes the plot 6 inches wide and 4 inches tall.

5. Plot the Zigzag Pattern
plt.plot(x, y, marker='o', linestyle='-', color='b', markersize=8, linewidth=2)
plt.plot(x, y, ...) plots the zigzag pattern.
marker='o' adds circular markers at each point.
linestyle='-' connects the points with a solid line.
color='b' makes the line blue.
markersize=8 controls the size of the circles.
linewidth=2 makes the line thicker.

6. Adjust the Axis for a Clean Look
ax.set_xlim(-1, size)
ax.set_ylim(-0.5, 1.5)
ax.set_xlim(-1, size): Ensures the x-axis starts a little before 0 and ends at size.
ax.set_ylim(-0.5, 1.5): Ensures the y-axis has enough space above and below the zigzag.
ax.set_xticks([])
ax.set_yticks([])
ax.set_frame_on(False)
ax.set_xticks([]): Removes x-axis tick marks.
ax.set_yticks([]): Removes y-axis tick marks.
ax.set_frame_on(False): Hides the frame for a clean look.

7. Display the Plot
plt.show()
Displays the zigzag pattern.

X Shaped pattern plot using python

 


import matplotlib.pyplot as plt

size=10

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

for i in range(size):

    plt.plot([i,size-1-i],[i,i],'bo')

    plt.plot([i,size-1-i],[size-1-i,size-1-i],'bo')


ax.set_xlim(-1,size)

ax.set_ylim(-1,size)

ax.set_xticks([])

ax.set_yticks([])

ax.set_frame_on(False)

plt.title('X shaped pattern')

plt.show()

#source code --> clcoding.com 

Code Explanation:

1. Import Required Libraries
import numpy as np
import matplotlib.pyplot as plt
numpy is imported but not used in the code. It is typically helpful for numerical computations.
matplotlib.pyplot is used to create the plot.

2. Define Grid Size
size = 10  # Change this for a larger or smaller X shape
This variable size determines how large the "X" shape will be.
It represents the number of rows and columns in the pattern.

3. Create Figure and Axis
fig, ax = plt.subplots(figsize=(6, 6))
plt.subplots() creates a figure (fig) and an axis (ax).
figsize=(6,6) sets the size of the figure to 6 inches by 6 inches.

4. Generate X-Shaped Pattern
for i in range(size):
    plt.plot([i, size - 1 - i], [i, i], 'bo')  # Top-left to bottom-right
    plt.plot([i, size - 1 - i], [size - 1 - i, size - 1 - i], 'bo')  # Bottom-left to top-right
This loop iterates from 0 to size-1.
The first plt.plot():
Plots points along the diagonal from top-left to bottom-right (\).
(i, i) and (size - 1 - i, i) define the start and end points of a line.
The second plt.plot():
Plots points along the diagonal from bottom-left to top-right (/).
(i, size - 1 - i) and (size - 1 - i, size - 1 - i) define the points.

5. Set Axis Limits
ax.set_xlim(-1, size)
ax.set_ylim(-1, size)
Ensures that the plotted points fit well within the graph area.
Limits are slightly beyond the grid (-1 to size) to provide padding.

6. Remove Axes for a Cleaner Look
ax.set_xticks([])
ax.set_yticks([])
ax.set_frame_on(False)
ax.set_xticks([]) and ax.set_yticks([]) remove the tick marks.
ax.set_frame_on(False) removes the surrounding box.

7. Display the Plot
plt.show()
This command displays the generated X-shaped pattern.


Plus(+)pattern plot using python


 import matplotlib.pyplot as plt


x_horiz=[-1,1]

y_horiz=[0,0]

x_vert=[0,0]

y_vert=[-1,1]

plt.plot(x_horiz,y_horiz,'b-',linewidth=3)

plt.plot(x_vert,y_vert,'b-',linewidth=3)

plt.xlim(-2,2)

plt.ylim(-2,2)

plt.grid(True)

plt.title('Plus pattern plot')

plt.show()

#source code --> clcoding.com 

Code Explanation:

1. Importing Matplotlib
import matplotlib.pyplot as plt
This imports matplotlib.pyplot, which is used for plotting in Python.

2. Defining Coordinates for the Plus (+) Shape
x_horiz = [-1, 1]  
y_horiz = [0, 0]  
This represents the horizontal line of the plus sign.
The line extends from x = -1 to x = 1, while keeping y = 0.
x_vert = [0, 0]    
y_vert = [-1, 1]   
This represents the vertical line of the plus sign.
The line extends from y = -1 to y = 1, while keeping x = 0.

3. Plotting the Horizontal and Vertical Lines
plt.plot(x_horiz, y_horiz, 'b-', linewidth=3)  
plt.plot(x_vert, y_vert, 'b-', linewidth=3)    
plt.plot(x_horiz, y_horiz, 'b-', linewidth=3)
Plots the horizontal line in blue (b).
Uses a solid line (-).
linewidth=3 makes the line thicker.
plt.plot(x_vert, y_vert, 'b-', linewidth=3)
Plots the vertical line using the same style.
Together, these lines form a plus (+) sign.

4. Setting Axis Limits
plt.xlim(-2, 2)  
plt.ylim(-2, 2)  
plt.xlim(-2, 2) sets the x-axis limits from -2 to 2.
plt.ylim(-2, 2) sets the y-axis limits from -2 to 2.
This ensures the plus sign is centered and visible.

5. Enabling Grid
plt.grid(True)
Adds a grid to the plot for better visualization.

6. Adding a Title
plt.title("Plus Pattern Plot")
Adds a title to the plot.

7. Displaying the Plot
plt.show()
This function renders and displays the plot.

Cross pattern plot


 import matplotlib.pyplot as plt

x=[0,0,-1,1,0,0]

y=[-1,1,0,0,-2,2]


plt.scatter(x,y,color='red')

plt.axhline(0,color='black',linewidth=0.5)

plt.axvline(0,color='black',linewidth=0.5)


plt.xlim(-2,2)

plt.ylim(-2,2)

plt.grid(True)


plt.title('Cross pattern plot')

plt.show()

#source code --> clcoding.com 

Code Explanation:

1. Importing Matplotlib
import matplotlib.pyplot as plt
This imports matplotlib.pyplot, which is a library used for creating plots in Python.

2. Defining Coordinates for the Cross
x = [0, 0, -1, 1, 0, 0]  # X-coordinates
y = [-1, 1, 0, 0, -2, 2]  # Y-coordinates
The x and y lists define the positions of points that form a cross shape.
The points are:
(0, -1)
(0, 1)
(-1, 0)
(1, 0)
(0, -2)
(0, 2)
These points create a cross pattern, where (0, 0) is the center.

3. Plotting the Points Using scatter
plt.scatter(x, y, color='red')
This function plots individual points at the given (x, y) coordinates.
The points are displayed as red dots.

4. Drawing Reference Lines
plt.axhline(0, color='black', linewidth=0.5)  # Draws a horizontal line at y=0
plt.axvline(0, color='black', linewidth=0.5)  # Draws a vertical line at x=0
These lines enhance visibility of the cross pattern:
plt.axhline(0): Draws a black horizontal line at y = 0.
plt.axvline(0): Draws a black vertical line at x = 0.
This helps center the cross visually.

5. Setting Plot Limits
plt.xlim(-2, 2)  # Limits the x-axis from -2 to 2
plt.ylim(-2, 2)  # Limits the y-axis from -2 to 2
This ensures that the cross is fully visible within a square frame.

6. Enabling Grid
plt.grid(True)
Adds a grid to the plot for better visualization.

7. Adding a Title
plt.title("Cross Pattern Plot")
This sets the title of the plot.

8. Displaying the Plot
plt.show()
Finally, plt.show() displays the plot.


Checkboard pattern plot using python

 


import numpy as np
import matplotlib.pyplot as plt

def plot_checkboard(size=8):
    board=np.indices((size,size)).sum(axis=0)%2
    
    plt.figure(figsize=(6,6))
    plt.imshow(board,cmap="gray",interpolation="nearest")
    
    plt.xticks([])
    plt.yticks([])
    plt.title('checkboard pattern plot')
    plt.show()
plot_checkboard(8)   

#source code --> clcoding.com 

Code Explanation:

Importing Required Libraries
import numpy as np
import matplotlib.pyplot as plt
numpy is used to generate the checkerboard pattern as a 2D array.
matplotlib.pyplot is used to plot the pattern.

Function Definition
def plot_checkerboard(size=8):
This function creates and plots a checkerboard of size × size squares.
The default board size is 8 × 8, like a chessboard.

Creating the Checkerboard Pattern
board = np.indices((size, size)).sum(axis=0) % 2
How This Works:
np.indices((size, size)) creates two 2D arrays of indices:
row_indices, col_indices = np.indices((8, 8))
Applying % 2:
If (row + col) % 2 == 0, it’s black (0).
If (row + col) % 2 == 1, it’s white (1).
Final Checkerboard (8×8) Array:
[[0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]]
This alternating 0s and 1s forms a checkerboard pattern.

Plotting the Checkerboard
plt.figure(figsize=(6, 6))
plt.imshow(board, cmap="gray", interpolation="nearest")
plt.figure(figsize=(6,6)) → Sets the figure size.
plt.imshow(board, cmap="gray", interpolation="nearest")
board: The checkerboard array.
cmap="gray": Uses grayscale colors (0 = black, 1 = white).
interpolation="nearest": Ensures sharp edges between squares.

Formatting for a Clean Look
plt.xticks([])
plt.yticks([])
plt.title("Checkerboard Pattern", fontsize=14, fontweight='bold')
plt.xticks([]), plt.yticks([]): Removes axis labels for a clean look.
plt.title(...): Adds a title to the plot.

Displaying the Plot
plt.show()
Displays the checkerboard plot.
When calling:
plot_checkerboard(8)
You get a black and white checkerboard with an 8×8 grid.

Circle Pattern Plot using Python

 


import numpy as np

import matplotlib.pyplot as plt

radius=1

num_points=50

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

x=radius*np.cos(theta)

y=radius*np.sin(theta)

fig,ax=plt.subplots()

ax.scatter(x,y,color='b',s=50)

ax.set_xlim(-1.2,1.2)

ax.set_ylim(-1.2,1.2)

ax.set_aspect('equal')

ax.axis('off')

plt.title("Circle pattern plot")

plt.show()

#source code --> clcoding.com 


Code Explanation:

1. Importing Required Libraries
import numpy as np
import matplotlib.pyplot as plt
numpy is used to generate numerical data, such as evenly spaced angles for plotting points.
matplotlib.pyplot is used to create the visualization.

2. Defining Circle Parameters
radius = 1
num_points = 50  # Number of dots
theta = np.linspace(0, 2 * np.pi, num_points)  # Angles for the circle
radius = 1: The radius of the circle.
num_points = 50: The number of dots to be placed around the circle.
np.linspace(0, 2 * np.pi, num_points):
This creates num_points evenly spaced values from 0 to 2π.
2π radians correspond to a full circle (360°).

3. Computing Circle Coordinates
x = radius * np.cos(theta)
y = radius * np.sin(theta)
np.cos(theta): Computes the x-coordinates of the points along the circle.
np.sin(theta): Computes the y-coordinates of the points along the circle.
Multiplying by radius ensures the points are scaled correctly.

4. Creating the Plot
fig, ax = plt.subplots()
ax.scatter(x, y, color='b', s=50)  # Scatter plot for dots
fig, ax = plt.subplots(): Creates a figure (fig) and an axis (ax) to plot on.
ax.scatter(x, y, color='b', s=50):
Uses scatter() to plot individual dots at (x, y).
color='b': Dots are blue (b for blue).
s=50: Size of each dot.

5. Setting Limits and Aspect Ratio
ax.set_xlim(-1.2, 1.2)
ax.set_ylim(-1.2, 1.2)
ax.set_aspect('equal')
ax.axis('off')  # Hide axes
ax.set_xlim(-1.2, 1.2): Sets x-axis limits slightly beyond the circle's radius for better visibility.
ax.set_ylim(-1.2, 1.2): Sets y-axis limits similarly.
ax.set_aspect('equal'): Ensures the aspect ratio is equal so the circle does not appear distorted.
ax.axis('off'): Hides the axes for a cleaner look.

6. Displaying the Plot
plt.show()
Displays the generated dotted circle.

Python Coding Challange - Question With Answer(01210225)

 


Explanation:

  1. String Indexing

    • The string "Python" consists of characters indexed as follows:

      P y t h o n 0 1 2 3 4 5
    • Each character has a corresponding index, starting from 0.
  2. String Slicing (x[2:5])

    • The slice notation [start:stop] extracts characters from index start up to (but not including) stop.
    • Here, x[2:5] means:
      • Start from index 2 ('t')
      • Go up to index 5 (which is 'n' but not included)
      • The extracted portion is 'tho'.

Output:


tho

Thursday, 20 February 2025

Star pattern plot using python

 


import matplotlib.pyplot as plt

import numpy as np


rows,cols=5,5


x=np.arange(cols)

y=np.arange(rows)

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

X=X.flatten()

Y=Y.flatten()


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

ax.scatter(X,Y,marker='*',s=300,color='gold',edgecolor='black')

ax.set_xlim(-1,cols)

ax.set_ylim(-1,rows)


ax.set_xticks([])

ax.set_yticks([])

ax.set_frame_on(False)

plt.show()

#source code --> clcoding.com 

Code Explanation:

Step 1: Import Required Libraries
import matplotlib.pyplot as plt
import numpy as np
matplotlib.pyplot (plt): Used for creating plots and visualizations.
numpy (np): Used for numerical operations, like generating coordinate grids.

Step 2: Define the Grid Size
rows, cols = 5, 5  
Sets the number of rows and columns in the star pattern.
The grid will have 5 rows and 5 columns, making a 5x5 arrangement.

Step 3: Create X and Y Coordinates
x = np.arange(cols)  # Creates an array [0, 1, 2, 3, 4] for x-coordinates
y = np.arange(rows)  # Creates an array [0, 1, 2, 3, 4] for y-coordinates
X, Y = np.meshgrid(x, y)
np.arange(cols): Generates an array [0, 1, 2, 3, 4] for the x-coordinates.
np.arange(rows): Generates an array [0, 1, 2, 3, 4] for the y-coordinates.
np.meshgrid(x, y): Creates a grid of (X, Y) coordinate pairs where each star will be placed.


Step 4: Convert 2D Arrays to 1D Lists
X = X.flatten()
Y = Y.flatten()
Converts X and Y from 2D arrays into 1D arrays.
This is needed because scatter() requires 1D lists of x and y coordinates.

Step 5: Create a Figure and Axis
fig, ax = plt.subplots(figsize=(6, 6))
Creates a figure (fig) and axis (ax) for the plot.
figsize=(6,6) sets the plot size to 6x6 inches.

Step 6: Plot Stars using scatter()
ax.scatter(X, Y, marker='*', s=300, color='gold', edgecolors='black')
scatter(X, Y, marker='*'): Plots stars (*) at each (X, Y) coordinate.
s=300: Controls the size of each star.
color='gold': Makes the stars golden.
edgecolors='black': Adds black outlines around the stars.


Step 7: Adjust Axis Limits
ax.set_xlim(-1, cols)  # Limits the x-axis from -1 to 5 (adds padding)
ax.set_ylim(-1, rows)  # Limits the y-axis from -1 to 5 (adds padding)
Sets x-axis from -1 to cols (5) to provide a little spacing.
Sets y-axis from -1 to rows (5) to prevent crowding.

Step 8: Remove Unnecessary Axes Information
ax.set_xticks([])  # Removes x-axis tick marks
ax.set_yticks([])  # Removes y-axis tick marks
ax.set_frame_on(False)  # Hides the axis border
Removes tick marks (set_xticks([]), set_yticks([])) to make the grid cleaner.
Hides the border (set_frame_on(False)) to focus only on the stars.

Step 9: Display the Plot
plt.show()
Displays the star pattern on the screen.

Hexagonal pattern plot using python

 


import matplotlib.pyplot as plt

import numpy as np

import matplotlib.patches as patches


def draw_hexagonal_pattern(rows, cols, hex_size=1):

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

    ax.set_xlim(-1, cols * 1.5)

    ax.set_ylim(-1, rows * np.sqrt(3))

    ax.set_aspect('equal')

    for row in range(rows):

        for col in range(cols):

            x = col * 1.5 * hex_size

            y = row * np.sqrt(3) * hex_size

            if col % 2 == 1:

                y += np.sqrt(3) / 2 * hex_size  

                hexagon = patches.RegularPolygon((x, y), numVertices=6, radius=hex_size, edgecolor='black', facecolor='lightblue')

            ax.add_patch(hexagon)

    plt.axis('off')  

    plt.show()

draw_hexagonal_pattern(6,6)

#source code --> clcoding.com 

Code Explanation:

Imports
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.patches as patches
matplotlib.pyplot: Used for plotting figures.
numpy: Provides mathematical functions (e.g., np.sqrt(3) for hexagonal height calculation).
matplotlib.patches: Contains shape objects like RegularPolygon, which we use to draw hexagons.

Function Definition
def draw_hexagonal_pattern(rows, cols, hex_size=1):
Defines a function draw_hexagonal_pattern that takes:
rows: Number of rows in the hexagonal pattern.
cols: Number of columns.
hex_size: The radius of each hexagon (default is 1).

Creating the Plot
    fig, ax = plt.subplots(figsize=(8, 8))
Creates a figure (fig) and axes (ax) to draw the pattern.
figsize=(8, 8): Sets the figure size to 8x8 inches.

    ax.set_xlim(-1, cols * 1.5)
    ax.set_ylim(-1, rows * np.sqrt(3))
    ax.set_aspect('equal')
ax.set_xlim(-1, cols * 1.5): Sets x-axis limits based on column count.
ax.set_ylim(-1, rows * np.sqrt(3)): Sets y-axis limits based on row count.
ax.set_aspect('equal'): Ensures hexagons retain their shape.

Loop to Create Hexagonal Grid
    for row in range(rows):
        for col in range(cols):
Loops through each row and column to place hexagons in a grid.

            x = col * 1.5 * hex_size
Calculates x-position: Each hexagon is spaced horizontally by 1.5 * hex_size.

            y = row * np.sqrt(3) * hex_size
Calculates y-position: Each hexagon is spaced vertically by √3 * hex_size.
            if col % 2 == 1:
                y += np.sqrt(3) / 2 * hex_size
Offsets every alternate column by √3/2 * hex_size to create a staggered effect.

Creating and Adding Hexagons
            hexagon = patches.RegularPolygon((x, y), numVertices=6, 
                                             radius=hex_size, edgecolor='black', 
                                             facecolor='lightblue')

Creates a hexagon using RegularPolygon:
(x, y): Center of the hexagon.
numVertices=6: Specifies it as a hexagon.
radius=hex_size: Defines the hexagon size.
edgecolor='black': Sets hexagon border color.
facecolor='lightblue': Sets fill color.

            ax.add_patch(hexagon)
Adds the hexagon to the plot (ax).
    plt.axis('off')  
    plt.show()
plt.axis('off'): Hides x and y axes.
plt.show(): Displays the figure.

Calling the Function
draw_hexagonal_pattern(6, 6)
Generates a hexagonal grid of 6 rows × 6 columns.


Python Coding Challange - Question With Answer(01200225)

 

Step-by-Step Execution:

  1. Function Definition:

    python
    def extend_list(lst):
    lst.extend([10])
    • The function extend_list(lst) takes a list lst as an argument.
    • It uses .extend([10]), which appends 10 to the existing list.
  2. List Initialization:

    python
    b = [5, 10, 15, 20]
    • A list b is created with four elements: [5, 10, 15, 20].
    • Initially, len(b) = 4.
  3. Function Call:

    python
    extend_list(b)
    • The list b is passed to extend_list(lst).
    • Inside the function, lst.extend([10]) adds 10 to the end of b.
    • Now, b becomes [5, 10, 15, 20, 10].
  4. Printing the Length:

    python
    print(len(b))
    • The updated list has 5 elements: [5, 10, 15, 20, 10].
    • len(b) returns 5.

Final Output:

5

Key Points:

  1. .extend([10]) appends 10 to the list.
  2.  Since lists are mutable, b is modified directly.
  3. The function does not return a new list; it updates the existing list.
  4. len(b) increases from 4 to 5 after the function call.

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

 

Step by Step Explanation:

Step 1: Define Class A

A class named A is created.

Inside A, we define a method show():

When called, this method returns the string "A".

Any object of A can call show() and get "A".

class B(A):

    pass

Step 2: Define Class B (Inheritance)

B is inheriting from A, meaning B gets all the attributes and methods of A.

The keyword pass means no additional methods or properties are added to B.

Since B does not have its own show() method, it will inherit the method from A.

print(B().show())

Step 3: Create an Object of B and Call show()

B() creates an instance of class B.

B().show() calls the show() method.

Since B does not have a show() method, it looks in class A (its parent class).

The show() method in A is executed, returning "A".

The print() function prints the returned value.

Final Output

A


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


 Step by Step Explanation:

class Multiply:
    def __mul__(self, other):
        return "Multiplication"

Step 1: Define a Class (Multiply)
The class Multiply is defined.
It has a special method __mul__(self, other).
This method overloads the * operator.
It takes self (the current object) and other (the value being multiplied).
Instead of performing actual multiplication, it always returns the string "Multiplication".

obj = Multiply()
Step 2: Create an Object (obj)
obj is an instance of Multiply.
Now, obj has access to the __mul__ method.

print(obj * 3)
Step 3: Multiplication (obj * 3)
This calls the overloaded __mul__ method:

obj.__mul__(3)
Instead of performing normal multiplication, __mul__ returns "Multiplication".

Final Output:

"Multiplication"

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

 

Step by Step Explanation:

def decorator(cls):

    cls.value = 42  # Adds a new attribute `value` to the class

    return cls  # Returns the modified class

Step 1: Define a Class Decorator

def decorator(cls):

This defines a function named decorator that takes a class (cls) as its parameter.

When applied, it will modify the class by adding new attributes or methods.


cls.value = 42

This adds a new attribute value to the class passed to the decorator.

Every class that uses @decorator will automatically have value = 42.

return cls

The modified class is returned.

This ensures that the original class remains functional but now has additional modifications.

@decorator  # Applying the decorator to the class

class Test:

    pass

Step 2: Apply the Decorator

@decorator

This applies the decorator function to the Test class.

Equivalent to manually writing:

class Test:

    pass

Test = decorator(Test)  # Modifies `Test` by adding `value = 42`When Test is passed into decorator(), it modifies Test by adding value = 42.

print(Test.value)  # Accessing the modified class attribute

Step 3: Print the New Attribute

Test.value

Since the decorator added value = 42, this now exists in the class.

print(Test.value) prints 42.

Final Output:

42

Popular Posts

Categories

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

Followers

Python Coding for Kids ( Free Demo for Everyone)