Tuesday, 18 February 2025

Diamond Pattern plot using python

 

import matplotlib.pyplot as plt

rows = 5

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

for i in range(rows):

    for j in range(rows - i - 1, rows + i):

        plt.scatter(j, -i, s=800, c='purple')

for i in range(rows - 2, -1, -1):

    for j in range(rows - i - 1, rows + i):

        plt.scatter(j, -(2 * rows - i - 2), s=800, c='purple')

plt.xlim(-0.5, 2 * rows - 1.5)

plt.ylim(-2 * rows + 1.5, 0.5)

plt.axis('off')

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

plt.title("Diamond Pattern Plot", fontsize=14)

plt.show()

#source code --> clcoding.com 

Code Explanation:

1. Importing Matplotlib

import matplotlib.pyplot as plt

This imports matplotlib.pyplot, which allows us to create plots.


2. Setting the Number of Rows

rows = 5

The variable rows controls the height of the upper half of the diamond.


3. Creating the Figure

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

Initializes a figure with dimensions 6x6 inches.

Generating the Diamond Shape

The diamond consists of two triangular halves:

Upper half (top to middle).

Lower half (middle to bottom).


4. Creating the Upper Part of the Diamond

for i in range(rows):

    for j in range(rows - i - 1, rows + i):

        plt.scatter(j, -i, s=800, c='red')

The outer loop (i) iterates over the rows.

The inner loop (j) controls the number of dots per row.

The range rows - i - 1 to rows + i ensures that dots expand outward as i increases.

plt.scatter(j, -i, s=800, c='red') places red dots at calculated positions.


5. Creating the Lower Part of the Diamond

for i in range(rows - 2, -1, -1):

    for j in range(rows - i - 1, rows + i):

        plt.scatter(j, -(2 * rows - i - 2), s=800, c='red')

The outer loop (i) iterates in reverse to form the lower half.

The inner loop (j) places dots in a shrinking pattern.

-(2 * rows - i - 2) correctly positions dots below the center.

Adjusting the Plot Appearance


6. Setting Axis Limits

plt.xlim(-0.5, 2 * rows - 1.5)

plt.ylim(-2 * rows + 1.5, 0.5)

plt.xlim(-0.5, 2 * rows - 1.5): Ensures the diamond is centered horizontally.

plt.ylim(-2 * rows + 1.5, 0.5): Ensures the full diamond is visible vertically.


7. Removing Axes and Adjusting Aspect Ratio

plt.axis('off')

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

plt.axis('off'): Removes grid lines and axis labels for a clean display.

plt.gca().set_aspect('equal', adjustable='datalim'): Ensures equal spacing between dots.


8. Adding a Title

plt.title("Diamond Pattern Plot", fontsize=14)

Displays the title of the plot.


9. Displaying the Pattern

plt.show()

Renders and displays the diamond pattern



Rectangle Pattern Plot using Python



import matplotlib.pyplot as plt

rows,cols=4,6

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

for i in range(rows):

    for j in range(cols):

        plt.scatter(j,-i,s=500,c='blue')

plt.xlim(-0.5,cols-0.5)

plt.ylim(-rows+0.5,0.5)

plt.axis('off')

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

plt.title('Reactangular pattern plot',fontsize=14)

plt.show()

#source code --> clcoding.com 

Code Explanation:

Importing Matplotlib:
import matplotlib.pyplot as plt
This imports Matplotlib's pyplot module, which is used for plotting.

Defining the grid size:
rows, cols = 4, 6
The pattern consists of 4 rows and 6 columns, forming a 4x6 rectangular grid.


Creating a figure:
plt.figure(figsize=(6, 4))
This creates a figure with a 6x4 inch size.

Generating the pattern using nested loops:
for i in range(rows):
    for j in range(cols):
        plt.scatter(j, -i, s=500, c='blue')
The outer loop (i) iterates over the rows.
The inner loop (j) iterates over the columns.
plt.scatter(j, -i, s=500, c='blue') places a blue dot at each (j, -i) coordinate:
j represents the x-coordinate (column index).
-i represents the y-coordinate (negative row index, keeping the origin at the top-left).
s=500 sets the dot size.
c='blue' sets the color to blue.

Setting the plot limits:
plt.xlim(-0.5, cols - 0.5)
plt.ylim(-rows + 0.5, 0.5)
plt.xlim(-0.5, cols - 0.5) ensures that the x-axis starts slightly before 0 and extends to cols - 1.
plt.ylim(-rows + 0.5, 0.5) adjusts the y-axis to properly contain all points.

Hiding the axis and adjusting the aspect ratio:
plt.axis('off')
plt.gca().set_aspect('equal', adjustable='datalim')
plt.axis('off') removes the x and y axes for a cleaner look.
plt.gca().set_aspect('equal', adjustable='datalim') ensures that the spacing between points remains uniform.

Adding a title:
plt.title("Rectangle Pattern Plot", fontsize=14)
Sets the title of the plot to "Rectangle Pattern Plot" with a font size of 14.

Displaying the plot:
plt.show()
Renders and displays the pattern.



Inverted Pyramid Pattern plot using python



 import matplotlib.pyplot as plt

rows = 5

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

for i in range(rows, 0, -1):

    for j in range(rows - i, rows + i - 1):

        plt.scatter(j, - (rows - i), s=800, c='red')

plt.xlim(-0.5, 2 * rows - 1.5)

plt.ylim(-rows + 0.5, 0.5)

plt.axis('off')

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

plt.title("Inverted Pyramid Pattern Plot", fontsize=14)

plt.show()

#source code --> clcoding.com 

Code explanation:

1. Importing Matplotlib

import matplotlib.pyplot as plt

This imports matplotlib.pyplot, which allows us to create scatter plots.


2. Defining the Number of Rows

rows = 5

rows = 5: Controls the height of the inverted pyramid.


3. Creating the Figure

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

Initializes a 6x6 inches plot.

Generating the Inverted Pyramid Shape


4. Looping to Generate the Pattern

for i in range(rows, 0, -1):  # Loop from rows down to 1

    for j in range(rows - i, rows + i - 1):  # Controls the number of dots per row

        plt.scatter(j, -(rows - i), s=800, c='red')

The outer loop (i) runs in reverse from rows down to 1, ensuring that the top row is widest and the bottom row is smallest.

The inner loop (j) determines how many dots are printed per row:

rows - i: Ensures proper horizontal spacing.

rows + i - 1: Expands outward as i decreases.

plt.scatter(j, -(rows - i), s=800, c='red') places red dots at calculated positions.

s=800: Controls the size of the dots.

-(rows - i): Ensures correct vertical placement.

Adjusting the Plot Appearance


5. Setting Axis Limits

plt.xlim(-0.5, 2 * rows - 1.5)

plt.ylim(-rows + 0.5, 0.5)

plt.xlim(-0.5, 2 * rows - 1.5): Ensures centered horizontal alignment.

plt.ylim(-rows + 0.5, 0.5): Ensures the entire inverted pyramid is visible.


6. Removing Axes and Adjusting Aspect Ratio

plt.axis('off')

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

plt.axis('off'): Hides grid lines and axis labels for a clean display.

plt.gca().set_aspect('equal', adjustable='datalim'): Maintains equal spacing between dots.


7. Adding a Title

plt.title("Inverted Pyramid Pattern Plot", fontsize=14)

Displays the title of the plot.


8. Displaying the Pattern

plt.show()

Renders and displays the inverted pyramid pattern.


Hollow Rectangle Pattern Plot using python

 


import matplotlib.pyplot as plt

def plot_hollow_rectangle(width, height):

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

    for x in range(width):

        plt.scatter(x, 0, s=200, c='black')

        plt.scatter(x, height-1, s=200, c='black')

        for y in range(height):

        plt.scatter(0, y, s=200, c='black')

        plt.scatter(width-1, y, s=200, c='black')

     plt.xlim(-1, width)

    plt.ylim(-1, height)

    plt.axis('off')

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

    plt.title("Hollow Rectangle Pattern Plot", fontsize=14)

    plt.show()

plot_hollow_rectangle(10, 6)

#source code --> clcoding.com 

Code Explanation:

1. Importing Required Library
import matplotlib.pyplot as plt
This imports matplotlib.pyplot, a popular library for creating plots and visualizations.

2. Defining the Function
def plot_hollow_rectangle(width, height):
This function takes two parameters: width (number of columns) and height (number of rows) to define the size of the rectangle.

3. Creating the Figure
plt.figure(figsize=(6, 6))
This initializes a new figure with a fixed size of 6x6 inches for consistent visualization.

4. Plotting the Top and Bottom Borders
for x in range(width):
    plt.scatter(x, 0, s=200, c='black')
    plt.scatter(x, height-1, s=200, c='black')
The loop iterates through all x positions from 0 to width-1:
plt.scatter(x, 0, s=200, c='black') → Plots points at the bottom of the rectangle.
plt.scatter(x, height-1, s=200, c='black') → Plots points at the top of the rectangle.

5. Plotting the Left and Right Borders
for y in range(height):
    plt.scatter(0, y, s=200, c='black')
    plt.scatter(width-1, y, s=200, c='black')
The loop iterates through all y positions from 0 to height-1:
plt.scatter(0, y, s=200, c='black') → Plots points at the left border.
plt.scatter(width-1, y, s=200, c='black') → Plots points at the right border.

6. Adjusting the Plot Limits
plt.xlim(-1, width)
plt.ylim(-1, height)
This ensures the plot is within the expected range, adding some padding for visibility.

7. Removing Axes and Setting Aspect Ratio
plt.axis('off')
plt.gca().set_aspect('equal', adjustable='datalim')
plt.axis('off') → Hides the axes for a cleaner appearance.
plt.gca().set_aspect('equal', adjustable='datalim') → Ensures that the aspect ratio of the points remains equal, preventing distortions.

8. Adding a Title
plt.title("Hollow Rectangle Pattern Plot", fontsize=14)
This adds a title to the plot for better understanding.

9. Displaying the Plot
plt.show()
This renders and displays the final hollow rectangle pattern.

Hollow Triangle Pattern Plot using python

 

import matplotlib.pyplot as plt

def plot_hollow_triangle(rows=5):

    # Define triangle vertices

    x1, y1 = 0, 0

    x2, y2 = rows - 1, 0

    x3, y3 = (rows - 1) / 2, np.sqrt(3) * (rows - 1) / 2  

    points = set()

    for i in range(rows):

        points.add((i, 0))

        lx = x1 + (x3 - x1) * i / (rows - 1)

        ly = y1 + (y3 - y1) * i / (rows - 1)

        points.add((lx, ly))

        rx = x2 + (x3 - x2) * i / (rows - 1)

        ry = y2 + (y3 - y2) * i / (rows - 1)

        points.add((rx, ry))

x_vals, y_vals = zip(*points)

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

    plt.scatter(x_vals, y_vals, color='black',s=400)

    plt.title("Hollow Equilateral Triangle Dot Pattern", fontsize=14)

    plt.xticks([])

    plt.yticks([])

    plt.gca().set_frame_on(False) 

    plt.show()

plot_hollow_triangle(rows=10)

#source code --> clcoding.com 

Code Explanation:

1. Importing Libraries
import matplotlib.pyplot as plt
matplotlib.pyplot is used for plotting the dot pattern.

2. Function Definition
def plot_hollow_triangle(rows=5):
Defines a function plot_hollow_triangle(rows=5), where rows determines the size of the triangle.

3. Defining Triangle Vertices
x1, y1 = 0, 0
x2, y2 = rows - 1, 0
x3, y3 = (rows - 1) / 2, np.sqrt(3) * (rows - 1) / 2
These coordinates represent the three vertices of an equilateral triangle:
(x1, y1) = (0, 0): Left vertex (bottom-left)
(x2, y2) = (rows - 1, 0): Right vertex (bottom-right)

4. Storing Boundary Points
points = set()
A set named points is created to store (x, y) coordinates for plotting.


5. Generating Points for Triangle Edges
for i in range(rows):
Iterates i times to generate dots along the three edges of the triangle.
Bottom Edge (Base)
points.add((i, 0))
Places i dots along the bottom edge (x-axis).
Left Edge (Interpolated)
lx = x1 + (x3 - x1) * i / (rows - 1)
ly = y1 + (y3 - y1) * i / (rows - 1)
points.add((lx, ly))
Uses linear interpolation to calculate intermediate points from (x1, y1) → (x3, y3).
Right Edge (Interpolated)
rx = x2 + (x3 - x2) * i / (rows - 1)
ry = y2 + (y3 - y2) * i / (rows - 1)
points.add((rx, ry))
Uses linear interpolation to calculate intermediate points from (x2, y2) → (x3, y3).

6. Plotting the Points
x_vals, y_vals = zip(*points)
plt.figure(figsize=(6, 6))
plt.scatter(x_vals, y_vals, color='black')
Extracts x and y coordinates from points and plots them using plt.scatter().

7. Adding a Title
plt.title("Hollow Equilateral Triangle Dot Pattern", fontsize=14, fontweight='bold')
Adds a title to the plot with bold font and size 14.

8. Removing Borders and Ticks
plt.xticks([])
plt.yticks([])
plt.gca().set_frame_on(False)
Removes x and y ticks for a clean look.
Removes the surrounding border (frame).

9. Displaying the Plot
plt.show()
Displays the triangle pattern.



Python Coding Challange - Question With Answer(01180225)

 


Step-by-step Execution:

  1. Define a Set:


    set1 = {10, 20, 30}
    • set1 is a set containing {10, 20, 30}.
  2. Remove an Element:

    set2 = set1.remove(20)
    • The .remove(20) method removes the element 20 from set1.
    • However, remove() does not return anything; it modifies set1 in place.
    • This means set2 gets assigned the return value of set1.remove(20), which is None.
  3. Print the Result:


    print(set2)
    • Since set2 = None, the output will be:

      None

Final Output:


None

Key Learning:

  • .remove() modifies the original set but returns None.
  • If you assign set2 = set1.remove(x), set2 will always be None.

25 Insanely Useful Python Code Snippets For Everyday Problems

 


📝 1. Swap Two Variables Without a Temp Variable


a, b = 5, 10
a, b = b, a
print(a, b)

Output:

10 5

📏 2. Check if a String is a Palindrome


def is_palindrome(s):
return s == s[::-1]
print(is_palindrome("madam"))

Output:


True

🔢 3. Find the Factorial of a Number

from math import factorial
print(factorial(5))

Output:

120

🎲 4. Generate a Random Password


import secrets, string
def random_password(length=10): chars = string.ascii_letters + string.digits + string.punctuation return ''.join(secrets.choice(chars) for _ in range(length))
print(random_password())

Output:


e.g., "A9$uT1#xQ%"

🔄 5. Flatten a Nested List


def flatten(lst):
return [i for sublist in lst for i in sublist]
print(flatten([[1, 2], [3, 4]]))

Output:


[1, 2, 3, 4]

🎭 6. Check if Two Strings are Anagrams


from collections import Counter
def is_anagram(s1, s2):
return Counter(s1) == Counter(s2)

print(is_anagram("listen", "silent"))

Output:


True

🛠️ 7. Merge Two Dictionaries

d1, d2 = {'a': 1}, {'b': 2}
merged = {**d1, **d2}
print(merged)

Output:

{'a': 1, 'b': 2}

📅 8. Get the Current Date and Time

from datetime import datetime
print(datetime.now())

Output:


2025-02-18 14:30:45.123456

🏃 9. Find Execution Time of a Function

import time
start = time.time() time.sleep(1)
print(time.time() - start)

Output:


1.001234 (approx.)

📂 10. Get the Size of a File

import os
print(os.path.getsize("example.txt"))

Output:


e.g., 1024 (size in bytes)

🔎 11. Find the Most Frequent Element in a List


from collections import Counter
def most_frequent(lst): return Counter(lst).most_common(1)[0][0]

print(most_frequent([1, 2, 3, 1, 2, 1]))

Output:

1

🔢 12. Generate Fibonacci Sequence


def fibonacci(n):
a, b = 0, 1 for _ in range(n): yield a a, b = b, a + b

print(list(fibonacci(10)))

Output:


[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

🔄 13. Reverse a List in One Line


lst = [1, 2, 3, 4]
print(lst[::-1])

Output:

[4, 3, 2, 1]

🔍 14. Find Unique Elements in a List

print(list(set([1, 2, 2, 3, 4, 4])))

Output:

[1, 2, 3, 4]

🎯 15. Check if a Number is Prime


def is_prime(n):
return n > 1 and all(n % i for i in range(2, int(n**0.5) + 1))

print(is_prime(7))

Output:

True

📜 16. Read a File in One Line


print(open("example.txt").read())

Output:


Contents of the file

📝 17. Count Words in a String

def word_count(s):
return len(s.split())

print(word_count("Hello world!"))

Output:

2

🔄 18. Convert a List to a Comma-Separated String

lst = ["apple", "banana", "cherry"]
print(", ".join(lst))

Output:

apple, banana, cherry

🔀 19. Shuffle a List Randomly

import random
lst = [1, 2, 3, 4] random.shuffle(lst)
print(lst)

Output:

e.g., [3, 1, 4, 2]

🔢 20. Convert a List of Strings to Integers

lst = ["1", "2", "3"]
print(list(map(int, lst)))

Output:

[1, 2, 3]

🔗 21. Get the Extension of a File

print("example.txt".split(".")[-1])

Output:

txt

📧 22. Validate an Email Address


import re
def is_valid_email(email): return bool(re.match(r"[^@]+@[^@]+\.[^@]+", email))

print(is_valid_email("test@example.com"))

Output:


True

📏 23. Find the Length of the Longest Word in a Sentence


def longest_word_length(s):
return max(map(len, s.split()))

print(longest_word_length("Python is awesome"))

Output:

7

🔠 24. Capitalize the First Letter of Each Word

print("hello world".title())

Output:


Hello World

🖥️ 25. Get the CPU Usage Percentage


import psutil
print(psutil.cpu_percent(interval=1))

Output:

e.g., 23.4

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 (1014) Python Coding Challenge (452) Python Quiz (94) 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)