Thursday, 27 March 2025

Swirl Bloom Pattern using Python

 


import numpy as np

import matplotlib.pyplot as plt

theta = np.linspace(0, 20 * np.pi, 2000)

radius = np.linspace(0, 10, 2000)

x = radius * np.cos(theta)

y = radius * np.sin(theta)

x += 0.5 * np.sin(10 * theta)

y += 0.5 * np.cos(10 * theta)

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

plt.plot(x, y, color='purple', linewidth=1)

plt.axis('off')

plt.gca().set_aspect('equal', adjustable='box')

plt.title('Swirl Bloom Pattern')

plt.show()

#source code --> clcoding.com

Code Explanation:

1. Importing Libraries

import numpy as np

import matplotlib.pyplot as plt

NumPy is used for mathematical operations, especially for generating arrays using linspace and performing trigonometric calculations.

Matplotlib is used for plotting the pattern using plt.plot().

 2. Generating the Swirl with Parametric Equations

theta = np.linspace(0, 20 * np.pi, 2000)

radius = np.linspace(0, 10, 2000)

theta: This is the angle in radians, ranging from 0 to 20π.

20 * np.pi means the spiral will have 10 complete turns (since one complete turn is 2π).

2000 points ensure a smooth and continuous curve.

radius: This linearly increases from 0 to 10, creating an outward bloom effect.

 3. Creating the Swirl Shape

x = radius * np.cos(theta)

y = radius * np.sin(theta)

Parametric Equations:

x=rcos(θ)

y=rsin(θ)

These equations generate a spiral by gradually increasing the radius while rotating around the center.

 4. Adding a Wavy Distortion

x += 0.5 * np.sin(10 * theta)

y += 0.5 * np.cos(10 * theta)

This introduces a wave-like perturbation to the spiral, making it bloom or ripple.

np.sin(10 * theta) and np.cos(10 * theta) add oscillations to both the x and y coordinates.

The factor 10 controls the number of small wave ripples (10 cycles per spiral).

The amplitude 0.5 controls the size of the distortions.

This gives the pattern a swirling, blooming effect.

 5. Plotting the Pattern

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

plt.plot(x, y, color='purple', linewidth=1)

plt.figure(figsize=(8, 8)): Creates a square figure with a size of 8x8 inches.

plt.plot(): Plots the x and y coordinates with a purple color and a thin line (linewidth=1).

 6. Adjusting Aesthetics

plt.axis('off')

plt.gca().set_aspect('equal', adjustable='box')

plt.title('Swirl Bloom Pattern')

plt.show()

plt.axis('off'): Hides the axis for a cleaner look.

plt.gca().set_aspect('equal', adjustable='box'): Maintains the aspect ratio to ensure the bloom shape is not distorted.

plt.title(): Displays the title.

plt.show(): Renders the plot.

 


Dragon Curve Pattern using Python

 


import numpy as np

import matplotlib.pyplot as plt

def dragon_curve(iterations):

    points = np.array([[0, 0], [1, 0]])

    direction = np.array([[0, -1], [1, 0]])

    for _ in range(iterations):

        new_points = []

        for i in range(len(points) - 1):

            p1, p2 = points[i], points[i + 1]

            midpoint = (p1 + p2) / 2

            rotated_vector = np.dot(direction, p2 - midpoint)

            new_point = midpoint + rotated_vector

            new_points.extend([p1, new_point])

        new_points.append(points[-1])

        points = np.array(new_points)

    return points

def plot_dragon_curve(iterations):

    points = dragon_curve(iterations)

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

    plt.plot(points[:, 0], points[:, 1], color='blue', linewidth=0.7)

    plt.axis('equal')

    plt.title("Dragon Curve Pattern")

    plt.show()

plot_dragon_curve(12)

#source code --> clcoding.com

Code Explanation:

1. Importing Required Libraries

import numpy as np

import matplotlib.pyplot as plt

numpy: A library used for numerical computing. It helps handle arrays efficiently.

matplotlib.pyplot: A library for plotting graphs and visualizing the generated fractal pattern.

 2. Defining the Dragon Curve Function

 def dragon_curve(iterations):

This function generates the Dragon Curve points based on the given number of iterations.

Each iteration refines the shape, making it more complex.

    points = np.array([[0, 0], [1, 0]])

points: This initializes the Dragon Curve with a straight-line segment between two points:

(0,0) → starting point

(1,0) → ending point

 direction = np.array([[0, -1], [1, 0]])

direction: This is a rotation matrix that rotates a point 90 degrees counterclockwise.

 3. Iterating to Generate the Fractal

    for _ in range(iterations):

This loop runs for the given number of iterations.

 Each iteration adds new points to make the shape more complex.

        new_points = []

new_points: This will store the new set of points after each iteration.

 4. Iterating Over the Current Points

        for i in range(len(points) - 1):

This loop goes through all adjacent points in the current list.

 It processes each segment in the shape.

           p1, p2 = points[i], points[i + 1]

p1: The starting point of the segment.

 p2: The ending point of the segment.

  midpoint = (p1 + p2) / 2

Finds the midpoint of the segment between p1 and p2.

           rotated_vector = np.dot(direction, p2 - midpoint)

p2 - midpoint: Finds the vector from the midpoint to p2.

 np.dot(direction, vector): Rotates this vector 90 degrees counterclockwise using the rotation matrix.

           new_point = midpoint + rotated_vector

Finds the new rotated point that will be inserted into the shape.

             new_points.extend([p1, new_point])

Adds the old point p1 and the new rotated point to the list.

 5. Completing the Iteration

        new_points.append(points[-1])

Ensures that the last point of the previous iteration remains in the shape.

        points = np.array(new_points)

Updates points with the new set of points after this iteration.

 6. Returning the Generated Points

    return points

After all iterations, the function returns the final set of points forming the fractal.

 7. Function to Plot the Dragon Curve

def plot_dragon_curve(iterations):

This function is responsible for visualizing the generated fractal.

   points = dragon_curve(iterations)

Calls dragon_curve(iterations) to generate the points.

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

Creates a new figure with a 6x6 inch size.

  plt.plot(points[:, 0], points[:, 1], color='blue', linewidth=0.7)

Plots the points using:

 X-coordinates (points[:, 0])

Y-coordinates (points[:, 1])

Blue color

 Line width of 0.7

    plt.axis('equal')

Ensures that the aspect ratio is equal, so the pattern does not look stretched.

    plt.title("Dragon Curve Pattern")

Adds a title to the plot.

    plt.show()

Displays the final fractal plot

 

Python Coding Challange - Question With Answer(01270325)




The given Python code has a recursive function named sum, but it will result in an infinite recursion error. Let's analyze why.

Understanding the Code:

python
def sum(num):
return num + sum(num - 1) # Recursive call without a base case
print(sum(2))

Step-by-Step Execution:

  1. print(sum(2)) calls sum(2).

  2. Inside sum(2), it tries to return 2 + sum(1).

  3. sum(1) then tries to return 1 + sum(0).

  4. sum(0) tries to return 0 + sum(-1), and so on...

Since there is no base case (a condition to stop recursion), the function keeps calling itself indefinitely, causing a RecursionError: maximum recursion depth exceeded.


Fixing the Code:

To make this function work correctly as a sum of natural numbers, we should add a base case:


def sum(num):
if num <= 0: # Base case to stop recursion return 0 return num + sum(num - 1)
print(sum(2)) # Output: 3 (2 + 1 + 0)

Correct Execution Flow:


sum(2) → 2 + sum(1) → 2 + (1 + sum(0)) → 2 + 1 + 0 = 3

Key Takeaways:

  • The original code lacks a base case, causing infinite recursion.

  • Recursion needs a stopping condition (base case) to prevent infinite loops.

  • The corrected function properly sums natural numbers recursively.


Check Now 400 Days Python Coding Challenges with Explanation

https://pythonclcoding.gumroad.com/l/sputu

Wednesday, 26 March 2025

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

 

Code Explanation:

1. Importing the Required Library

import heapq
The heapq module provides efficient operations for working with heaps in Python.

A heap is a specialized tree-based data structure that is mainly used for priority queues.

In this code, heapq is used to efficiently find the kth largest element.

2. Defining the Function

def find_kth_largest(nums, k):
    heapq.heapify(nums)
    return heapq.nlargest(k, nums)[0]
find_kth_largest(nums, k): This function returns the kth largest element in the list nums.

Parameters:
nums → A list of integers.
k → The rank of the largest element to find.

3. Using heapq.heapify()
heapq.heapify(nums)
heapify(nums) converts the list nums into a min-heap in O(n) time.

In a min-heap, the smallest element is always at the root.
Heap is not explicitly used further in this code, but it makes subsequent operations like nlargest() faster.

4. Finding the Kth Largest Element Using heapq.nlargest()
return heapq.nlargest(k, nums)[0]
heapq.nlargest(k, nums) returns the k largest elements from the list in descending order.

[0] → The first element of this list is the kth largest element.


5. Printing the Output
print(find_kth_largest([3,2,3,1,2,4,5,5,6], 4))
The function call evaluates to 4.

Final Output:

4

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

 


Code Explanation:

1. Importing the Required Library
import heapq
heapq is a Python library that provides efficient heap operations.

The heapq.nsmallest() function is used to find the k smallest elements from a list based on a specific key.

2. Defining the Function
def k_closest(points, k):
    distance = lambda x: x[0]**2 + x[1]**2
    return heapq.nsmallest(k, points, key=distance)
points: List of coordinates representing points on a 2D plane.
k: Number of closest points to find.
distance: A lambda function that calculates the Euclidean distance squared from the origin using the 
​heapq.nsmallest(): Returns the k closest points based on their calculated distances.

3. Applying heapq.nsmallest()
The function finds the two closest points by comparing the distances:

(3,3) → Distance = 18

(-2,4) → Distance = 20

(5,-1) → Distance = 26

The two points with the smallest distances are (3,3) and (-2,4).

4.Final Output
print(k_closest([[3,3],[5,-1],[-2,4]], 2)) # Output?
The output is:
[[3,3], [-2,4]]


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

 


Code Explanation:

Step 1: Importing PyTorch

import torch imports the PyTorch library, which is commonly used for machine learning, deep learning, and scientific computing.

Step 2: Creating a Tensor (Matrix)

matrix = torch.tensor([[4.0, 7.0], [2.0, 6.0]])

A tensor in PyTorch is similar to a NumPy array but optimized for GPU acceleration.

Step 3: Calculating the Matrix Norm

norm_value = torch.linalg.norm(matrix)

torch.linalg.norm() computes the Frobenius norm by default.

The Frobenius norm of a matrix 𝐴

Step 4: Printing the Result

print("Matrix Norm:", norm_value)

This prints the calculated Frobenius norm value.

Final Output:

Matrix Norm: 11.18

Spirograph Pattern using Python

 

import numpy as np

import matplotlib.pyplot as plt

def spirograph(a, b, delta, num_points=1000):

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

    x = np.sin(a * t + delta)

    y = np.cos(b * t)

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

    plt.plot(x, y, color='purple', linewidth=1.5)

    plt.axis("equal")

    plt.axis("off")

    plt.title("Spirograph Pattern", fontsize=14)

    plt.show()

spirograph(a=5,b=4,delta=np.pi/2)

#source code --> clcoding.com 

Code Explanation:

1. Importing Libraries

import numpy as np

import matplotlib.pyplot as plt

numpy → Used for numerical operations and generating arrays efficiently.

 

matplotlib.pyplot → Used for creating visualizations in Python.

 

2. Generating Data for the Plot

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

r = 1 + 0.5 * np.sin(4 * theta)

np.linspace(0, 2 * np.pi, 100) → Generates 100 evenly spaced values between 0 and 2π (360°).

 

theta → Represents the angular values in radians, making it perfect for a polar plot.

 

np.sin(4 * theta) → Calculates the sine of the angular values. The 4 in the expression means the sine wave will complete 4 oscillations in one full rotation (2π).

r = 1 + 0.5 * sin(4 * theta) →

1 → Base radius (Constant Offset)

0.5 * sin(4 * theta) → Creates the sinusoidal oscillations.

This makes the radius vary between 0.5 to 1.5 in a wave-like pattern.

 3. Creating the Plot

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

plt.figure(figsize=(8, 6)) → Creates a figure of size 8x6 inches. This helps in adjusting the dimensions for better visibility.

 4. Setting Up the Polar Plot

ax = plt.subplot(111, polar=True)

plt.subplot() → Creates a subplot inside the figure.

111 → Means 1 row, 1 column, and this is the 1st subplot.

polar=True → Specifies that the plot will be in polar coordinates instead of Cartesian.

 5. Plotting the Data

ax.plot(theta, r, color='blue', linewidth=2)

ax.plot() → Plots the data on the polar plot using the generated theta (angles) and r (radius values).

color='blue' → Makes the curve blue.

linewidth=2 → Sets the line thickness to 2 points for clearer visibility.

 6. Adding Title

ax.set_title('Basic Polar Plot with Sinusoidal Pattern', va='bottom')

ax.set_title() → Adds a title to the polar plot.

va='bottom' → Aligns the title to the bottom of the plot.

 7. Displaying the Plot

plt.show()

plt.show() → Displays the plot on the screen.


Polar Pattern Plot using Python

 


import numpy as np

import matplotlib.pyplot as plt

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

r = 1 + 0.5 * np.sin(4 * theta)

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

ax = plt.subplot(111, polar=True)

ax.plot(theta, r, color='blue', linewidth=2)

ax.set_title('Basic Polar Plot  Pattern', va='bottom')

plt.show()

#source code --> clcoding.com 


Code Explanation:

1. Importing Libraries

import numpy as np

import matplotlib.pyplot as plt

numpy → Used for numerical operations and generating arrays efficiently.

 matplotlib.pyplot → Used for creating visualizations in Python.

 2. Generating Data for the Plot

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

r = 1 + 0.5 * np.sin(4 * theta)

np.linspace(0, 2 * np.pi, 100) → Generates 100 evenly spaced values between 0 and 2π (360°).

theta → Represents the angular values in radians, making it perfect for a polar plot

np.sin(4 * theta) → Calculates the sine of the angular values. The 4 in the expression means the sine wave will complete 4 oscillations in one full rotation (2π).

r = 1 + 0.5 * sin(4 * theta) →

1 → Base radius (Constant Offset)

0.5 * sin(4 * theta) → Creates the sinusoidal oscillations.

This makes the radius vary between 0.5 to 1.5 in a wave-like pattern.

 3. Creating the Plot

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

plt.figure(figsize=(8, 6)) → Creates a figure of size 8x6 inches. This helps in adjusting the dimensions for better visibility.

 4. Setting Up the Polar Plot

ax = plt.subplot(111, polar=True)

plt.subplot() → Creates a subplot inside the figure.

111 → Means 1 row, 1 column, and this is the 1st subplot.

polar=True → Specifies that the plot will be in polar coordinates instead of Cartesian.

 5. Plotting the Data

ax.plot(theta, r, color='blue', linewidth=2)

ax.plot() → Plots the data on the polar plot using the generated theta (angles) and r (radius values).

color='blue' → Makes the curve blue.

linewidth=2 → Sets the line thickness to 2 points for clearer visibility.

 6. Adding Title

ax.set_title('Basic Polar Plot with Sinusoidal Pattern', va='bottom')

ax.set_title() → Adds a title to the polar plot.

va='bottom' → Aligns the title to the bottom of the plot.

 7. Displaying the Plot

plt.show()

plt.show() → Displays the plot on the screen.


Pedigree Analysis Chart Using Python

 


import networkx as nx
import matplotlib.pyplot as plt

G = nx.DiGraph()

nodes = ['Grandfather', 'Grandmother', 'Father', 'Mother', 'Child 1', 'Child 2']
G.add_nodes_from(nodes)
edges = [('Grandfather', 'Father'), 
         ('Grandmother', 'Father'),
         ('Father', 'Child 1'), 
         ('Father', 'Child 2'), 
         ('Mother', 'Child 1'), 
         ('Mother', 'Child 2')]
G.add_edges_from(edges)

plt.figure(figsize=(8, 6))
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels=True, node_size=3000, node_color='skyblue', font_size=10, font_weight='bold', edge_color='gray')
plt.title('Pedigree Analysis Chart')
plt.show()
#source code --> clcoding.com 

Code Explanation

1. Import Libraries

import networkx as nx

import matplotlib.pyplot as plt

networkx is used for creating and managing graphs (e.g., family trees).

matplotlib.pyplot is used for visualizing the graph.

 2. Create a Graph

G = nx.DiGraph()

DiGraph() creates a Directed Graph where edges have a direction (e.g., parent to child).

 3. Add Nodes (Individuals)

nodes = ['Grandfather', 'Grandmother', 'Father', 'Mother', 'Child 1', 'Child 2']

G.add_nodes_from(nodes)

Nodes represent individuals in the family.

 add_nodes_from() efficiently adds multiple nodes at once.

 4. Add Edges (Relationships)

edges = [('Grandfather', 'Father'),

         ('Grandmother', 'Father'),

         ('Father', 'Child 1'),

         ('Father', 'Child 2'),

         ('Mother', 'Child 1'),

         ('Mother', 'Child 2')]

G.add_edges_from(edges)

Edges represent parent-child relationships using tuples (Parent, Child).

 add_edges_from() adds multiple relationships.

 5. Configure and Draw the Graph

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

pos = nx.spring_layout(G)

plt.figure(figsize=(8, 6)) sets the figure size for better visibility.

 nx.spring_layout(G) positions nodes using a force-directed layout, providing a natural and balanced appearance.

 nx.draw(G, pos, with_labels=True, node_size=3000, node_color='skyblue', font_size=10, font_weight='bold', edge_color='gray')

nx.draw() renders the graph.

 with_labels=True displays the node names.

 node_size=3000 controls the size of nodes.

node_color='skyblue' makes the nodes visually distinct.

 font_size=10, font_weight='bold' makes the labels more readable.

 edge_color='gray' sets the color of the relationships.

 6. Add Title and Display the Chart

plt.title('Pedigree Analysis Chart')

plt.show()

plt.title() adds a title to the chart.

 plt.show() displays the final output

Python Coding Challange - Question With Answer(01260325)

 


Explanation of the Code

Code Breakdown

def calcNums(*nums):
  • The function calcNums takes a variable number of arguments (*nums), meaning you can pass any number of values to it.

  • The * (asterisk) operator allows the function to accept multiple arguments as a tuple.

calculation = 1
  • Initializes calculation with 1 since multiplication starts from 1.

for num in nums:
calculation *= num
  • Iterates over each number in nums, multiplying calculation by each value.


return calculation
  • Returns the final product of all numbers.

print(calcNums(1,3,4,5))
  • Calls the function with arguments 1, 3, 4, 5.

Step-by-Step Execution

    nums = (1, 3, 4, 5)
  1. calculation starts at 1

  2. Multiply step-by-step:

      1 * 1 = 1 
      1 * 3 = 3 
      3 * 4 = 12 
      12 * 5 = 60
  3. The function returns 60, which is printed.

Final Output:


60

CHECK NOW PYTHON INTERVIEW QUESTIONS AND ANSWERS

https://pythonclcoding.gumroad.com/l/ylxbs

Popular Posts

Categories

100 Python Programs for Beginner (118) AI (150) 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 (216) Data Strucures (13) Deep Learning (67) 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 (185) Meta (24) MICHIGAN (5) microsoft (9) Nvidia (8) Pandas (11) PHP (20) Projects (32) Python (1215) 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)