Showing posts with label Python Tips. Show all posts
Showing posts with label Python Tips. Show all posts

Sunday, 23 February 2025

Hourglass 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 to generate numerical data (e.g., linspace for smooth curves).
matplotlib.pyplot is used for visualization.

Define X-Coordinates for the Plot
x = np.linspace(-1, 1, 100)
np.linspace(-1, 1, 100): Generates 100 evenly spaced points between -1 and 1.
These x values will be used to define the hourglass shape.

Define Y-Coordinates for Upper and Lower Triangles
y_upper = 1 - abs(x)  
y_lower = abs(x) - 1  
y_upper = 1 - abs(x):
This represents the upper inverted triangle.
As x moves from -1 to 1, the y values decrease from 1 to 0 symmetrically.
y_lower = abs(x) - 1:
This represents the lower triangle.
As x moves from -1 to 1, the y values increase from -1 to 0 symmetrically.
Together, they form an hourglass shape!

Create the Plot
fig, ax = plt.subplots(figsize=(6, 6))
fig, ax = plt.subplots(figsize=(6, 6)):
Creates a square-shaped figure of size 6x6.

Fill the Upper and Lower Triangles
ax.fill_between(x, y_upper, 1, color="royalblue", alpha=0.7)  
ax.fill_between(x, y_lower, -1, color="tomato", alpha=0.7)
fill_between(x, y_upper, 1, color="royalblue", alpha=0.7):
Fills the area between y_upper and 1 with blue.
fill_between(x, y_lower, -1, color="tomato", alpha=0.7):
Fills the area between y_lower and -1 with red.
alpha=0.7:
Transparency of 70% (makes colors blend better).

Adjust Axis Limits and Appearance
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.set_xlim(-1.2, 1.2): Expands x-axis slightly beyond -1 and 1.
ax.set_ylim(-1.2, 1.2): Expands y-axis slightly beyond -1 and 1.
ax.set_xticks([]): Removes x-axis tick marks.
ax.set_yticks([]): Removes y-axis tick marks.
ax.set_frame_on(False): Removes the border around the plot.

Add a Symmetry Line
ax.axhline(0, color="black", linewidth=1.2, linestyle="--")
axhline(0, color="black", linewidth=1.2, linestyle="--"):
Draws a dashed black line at y = 0 to emphasize symmetry.

Add Title and Display Plot
ax.set_title("Hourglass Pattern Plot", fontsize=14, fontweight="bold")
plt.show()
set_title("Hourglass Pattern Plot", fontsize=14, fontweight="bold"):
Adds a bold title with font size 14.
plt.show():
Displays the final hourglass pattern.

Thursday, 13 February 2025

Python 3.14: What’s New in the Latest Update?

 

Python 3.14 is here, bringing exciting new features, performance improvements, and enhanced security. As one of the most anticipated updates in Python’s evolution, this version aims to streamline development while maintaining Python’s simplicity and power. Let’s explore the key changes and updates in Python 3.14.

1. Improved Performance and Speed

Python 3.14 introduces optimizations in its interpreter, reducing execution time for various operations. Some notable improvements include:

  • Enhanced Just-In-Time (JIT) compilation for better execution speed.

  • More efficient memory management to reduce overhead.

  • Faster startup time, benefiting large-scale applications and scripts.

2. New Features in the Standard Library

Several new additions to the standard library make Python even more versatile:

  • Enhanced math module: New mathematical functions for better numerical computations.

  • Upgraded asyncio module: Improved asynchronous programming with better coroutine handling.

  • New debugging tools: More robust error tracking and logging capabilities.

3. Security Enhancements

Security is a key focus in Python 3.14, with several updates to protect applications from vulnerabilities:

  • Stronger encryption algorithms in the hashlib module.

  • Improved handling of Unicode security concerns.

  • Automatic detection of potential security issues in third-party dependencies.

4. Syntax and Language Improvements

Python 3.14 introduces minor yet impactful changes in syntax and usability:

  • Pattern matching refinements: More intuitive syntax for structured pattern matching.

  • Better type hinting: Improved static analysis and error checking.

  • New decorators for function optimizations: Making code more readable and maintainable.

5. Deprecations and Removals

To keep Python efficient and modern, some outdated features have been deprecated:

  • Older modules with security risks are removed.

  • Legacy syntax that slows down execution has been phased out.

  • Deprecated APIs in the standard library have been replaced with modern alternatives.

Conclusion

Python 3.14 brings a mix of performance boosts, security improvements, and new functionalities that enhance the developer experience. Whether you're a seasoned Python programmer or just getting started, this update ensures a smoother and more efficient coding journey.

Download: https://www.python.org/downloads/

Saturday, 28 December 2024

Python Coding Challange - Question With Answer(01281224)

 


What will the following code output?

print([x**2 for x in range(10) if x % 2 == 0])

  • [0, 1, 4, 9, 16]
  • [0, 4, 16, 36, 64]
  • [4, 16, 36, 64]
  • [1, 4, 9, 16, 25]

1. List Comprehension Syntax

This code uses list comprehension, a concise way to create lists in Python. The general structure is:

[expression for item in iterable if condition]
  • expression: What you want to compute for each item.
  • item: The current element from the iterable.
  • iterable: A sequence, such as a list or range.
  • if condition: A filter to include only items that satisfy the condition.

2. Components of the Code

a. range(10)

  • range(10) generates numbers from 0 to 9.

b. if x % 2 == 0

  • This is the filter condition.
  • x % 2 calculates the remainder when x is divided by 2.
    • If the remainder is 0, the number is even.
  • This condition selects only the even numbers from 0 to 9.

c. x**2

  • For each even number, x**2 computes the square of x.

3. Step-by-Step Execution

Step 1: Generate Numbers from range(10)

The numbers are:


0, 1, 2, 3, 4, 5, 6, 7, 8, 9

Step 2: Apply the Condition if x % 2 == 0

Keep only even numbers:

0, 2, 4, 6, 8

Step 3: Compute the Expression x**2

Calculate the square of each even number:

  • 02=00^2 = 0
  • 22=42^2 = 4
  • 42=164^2 = 16
  • 62=366^2 = 36
  • 82=648^2 = 64

Step 4: Create the Final List

The resulting list is:

[0, 4, 16, 36, 64]

4. Output

The code prints:

[0, 4, 16, 36, 64]

Thursday, 19 December 2024

Python Tips of the day - 19122024

 


Python Tip: Use List Comprehensions for Simplicity

When working with lists in Python, you’ll often find yourself creating a new list by performing some operation on each element of an existing iterable, such as a list or range. While you can use a traditional for loop to achieve this, Python offers a cleaner and more concise way: list comprehensions.

The Traditional Way: Using a for Loop

Here’s how you might traditionally create a list of squares using a for loop:

# The traditional way
result = []
for x in range(10):
      result.append(x**2)

In this code:

  • An empty list, result, is initialized.

  • A for loop iterates through numbers from 0 to 9 (using range(10)).

  • Each number, x, is squared (x**2) and appended to the result list.

While this code works, it’s somewhat verbose and introduces multiple lines of code for a simple operation.

The Pythonic Way: Using List Comprehensions

With a list comprehension, you can achieve the same result in a single, elegant line of code:

# The Pythonic way
result = [x**2 for x in range(10)]

How It Works:

The syntax of a list comprehension is:

[expression for item in iterable]

Breaking it down for our example:

  • Expression: x**2 – This is the operation applied to each item in the iterable.

  • Item: x – Represents each value in the iterable.

  • Iterable: range(10) – Generates numbers from 0 to 9.

For each number in the range, Python calculates x**2 and adds it to the resulting list, all in a single line.

Comparing the Outputs

Both methods produce the same result:

print(result) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Why Use List Comprehensions?

  1. Conciseness: List comprehensions reduce multiple lines of code to a single line, making your code shorter and easier to read.

  2. Readability: Once you’re familiar with the syntax, list comprehensions are more intuitive than traditional loops.

  3. Performance: List comprehensions are generally faster than for loops because they are optimized at the C level in Python.

Advanced Example: Adding Conditions

You can enhance list comprehensions by adding conditional statements. For example, to include only the squares of even numbers:

result = [x**2 for x in range(10) if x % 2 == 0]
print(result) # Output: [0, 4, 16, 36, 64]

Here:

  • The condition if x % 2 == 0 filters the numbers, including only those divisible by 2.

Practical Applications

List comprehensions are not just limited to simple operations. Here are a few practical examples:

1. Convert Strings to Uppercase

words = ['hello', 'world']
uppercase_words = [word.upper() for word in words]
print(uppercase_words) # Output: ['HELLO', 'WORLD']

2. Flatten a Nested List

nested_list = [[1, 2], [3, 4], [5, 6]]
flattened = [num for sublist in nested_list for num in sublist]
print(flattened) # Output: [1, 2, 3, 4, 5, 6]

3. Generate a List of Tuples

pairs = [(x, y) for x in range(3) for y in range(3)]
print(pairs)
# Output: [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

Conclusion

List comprehensions are a powerful tool in Python that make your code more concise, readable, and efficient. Whenever you find yourself writing a loop to create a list, consider using a list comprehension instead. It’s one of the many features that makes Python both elegant and practical.

Wednesday, 18 December 2024

Python Tips of the day - 18122024

 

Python Tip: Use enumerate for Indexed Loops

When working with loops in Python, it's common to come across scenarios where you need both the index and the value of elements in a list. Beginners often use a manual approach to achieve this, but there's a much cleaner and Pythonic way: the enumerate function.

The Manual Way: Using a Counter Variable

A common approach many new programmers use involves creating a separate counter variable and incrementing it inside the loop:

# The manual way
i = 0
for item in my_list:
    print(i, item)
    i += 1

While this works, it's not ideal. The counter variable i adds unnecessary boilerplate code, and forgetting to increment i can lead to bugs. Plus, the code doesn't leverage Python's simplicity and readability.

The Pythonic Way: Using enumerate

Python's built-in enumerate function simplifies this task. It automatically provides both the index and the value for each iteration, eliminating the need for a separate counter variable:

# The Pythonic way
for i, item in enumerate(my_list):
      print(i, item)

This approach is cleaner, requires fewer lines of code, and is less prone to errors.

How enumerate Works

The enumerate function takes an iterable (like a list, tuple, or string) and returns an iterator that yields pairs of index and value. By default, the index starts at 0, but you can specify a different starting point using the start parameter.

Here’s an example with a custom starting index:

my_list = ['apple', 'banana', 'cherry']
for i, item in enumerate(my_list, start=1):
      print(i, item)

Output:

1 apple
2 banana
3 cherry

Benefits of Using enumerate

  1. Cleaner Code: Reduces boilerplate code by eliminating the need for a counter variable.

  2. Readability: Makes the code easier to read and understand.

  3. Error Prevention: Avoids common mistakes like forgetting to increment the counter variable.

Practical Example

Suppose you're working on a program that processes a list of tasks, and you want to display their indices alongside the task names. Using enumerate, you can write:

tasks = ['Wash dishes', 'Write blog post', 'Read a book']
for index, task in enumerate(tasks):
      print(f"{index}: {task}")

Output:

0: Wash dishes
1: Write blog post
2: Read a book

This simple structure allows you to focus on the task at hand without worrying about managing a separate counter variable.

Advanced Use Case: Working with Nested Loops

enumerate can also be used in nested loops when working with multidimensional data:

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row_index, row in enumerate(matrix):
 for col_index, value in enumerate(row): 
     print(f"({row_index}, {col_index}): {value}")

Output:

(0, 0): 1
(0, 1): 2
(0, 2): 3
(1, 0): 4
(1, 1): 5
(1, 2): 6
(2, 0): 7
(2, 1): 8
(2, 2): 9

Conclusion

The enumerate function is a simple yet powerful tool that helps you write cleaner and more Pythonic code. Whenever you find yourself managing a counter variable in a loop, consider switching to enumerate. It’s one of those little tricks that can make a big difference in your coding experience.

So the next time you're iterating over a list and need the index, ditch the manual counter and embrace the elegance of enumerate!

Popular Posts

Categories

100 Python Programs for Beginner (96) AI (39) Android (24) AngularJS (1) Api (2) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (191) C (77) C# (12) C++ (83) Course (67) Coursera (249) Cybersecurity (25) Data Analysis (2) Data Analytics (2) data management (11) Data Science (148) 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 (11) 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 (84) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (4) Pandas (4) PHP (20) Projects (29) pyth (1) Python (1022) Python Coding Challenge (454) Python Quiz (108) 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)