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

Saturday 11 May 2024

Type Hints in Python

 Type hints in Python are an excellent tool for improving code quality and maintainability, especially in larger projects. 

from typing import Optional

class TreeNode:

    def __init__(self, value: int) -> None:

        self.value = value

        self.left: Optional['TreeNode'] = None

        self.right: Optional['TreeNode'] = None

#clcoding.com

class LinkedListNode:

    def __init__(self, value: int, next_node: 'LinkedListNode' = None) -> None:

        self.value = value

        self.next = next_node

#clcoding.com

from typing import Optional

class TreeNode:

    def __init__(self, value: int) -> None:

        self.value = value

        self.left: Optional['TreeNode'] = None

        self.right: Optional['TreeNode'] = None

#clcoding.com

from typing import TypeVar

class Animal:

    def speak(self) -> str:

        raise NotImplementedError

class Dog(Animal):

    def speak(self) -> str:

        return "Woof!"

T = TypeVar('T', bound=Animal)

def make_sound(animal: T) -> str:

    return animal.speak()

#clcoding.com

from typing import Callable

def apply_func(func: Callable[[int, int], int], a: int, b: int) -> int:

    return func(a, b)

#clcoding.com

from typing import Iterable, TypeVar

T = TypeVar('T')

def process_items(items: Iterable[T]) -> None:

    for item in items:

        # Process each item

        pass

#clcoding.com

from typing import TypeVar, Iterable

T = TypeVar('T')

def first_element(items: Iterable[T]) -> T:

    return next(iter(items))

#clcoding.com

from typing import List, Tuple

Point = Tuple[int, int]

Polygon = List[Point]

def area(polygon: Polygon) -> float:

    # Calculate area of polygon

    pass

#clcoding.com

from typing import Union
def square_root(num: Union[int, float]) -> Union[int, float]:
    return num ** 0.5

#clcoding.com
from typing import Optional

def greet(name: Optional[str]) -> str:
    if name:
        return f"Hello, {name}!"
    else:
        return "Hello, anonymous!"

#clcoding.com

Automating File Compression with gzip

 

Code:

import gzip

import shutil


def compress_file(input_file, output_file):

    with open(input_file, 'rb') as f_in:

        with gzip.open(output_file, 'wb') as f_out:

            shutil.copyfileobj(f_in, f_out)


# Example usage

input_filename = 'clcoding.txt'

output_filename = 'clcoding.txt.gz'

compress_file(input_filename, output_filename)

#clcoding.com 

Explanation:

Let's break down the code step by step:

import gzip: This line imports the gzip module, which provides functionalities for working with gzip-compressed files in Python. The gzip module allows you to create, read, and write gzip-compressed files.

import shutil: This line imports the shutil module, which provides a higher-level interface for file operations. In this script, shutil is used to copy the contents of one file to another efficiently.

def compress_file(input_file, output_file):: This line defines a function named compress_file that takes two parameters: input_file (the path to the file to be compressed) and output_file (the path where the compressed file will be saved).

with open(input_file, 'rb') as f_in:: This line opens the input file (input_file) in binary read mode ('rb') using the open() function. It uses a context manager (with statement) to automatically close the file when the block is exited. The file object is assigned to the variable f_in.

with gzip.open(output_file, 'wb') as f_out:: This line opens the output file (output_file) in gzip-compressed write mode ('wb') using gzip.open(). Similar to the previous with statement, it also uses a context manager to automatically close the file when the block is exited. The compressed file object is assigned to the variable f_out.

shutil.copyfileobj(f_in, f_out): This line copies the contents of the input file (f_in) to the gzip-compressed output file (f_out). It efficiently copies data between file objects without loading the entire file into memory.

input_filename = 'clcoding.txt': This line defines a variable input_filename and assigns it the name of the input file (clcoding.txt). This file will be compressed.

output_filename = 'clcoding.txt.gz': This line defines a variable output_filename and assigns it the name of the output file (clcoding.txt.gz). This file will store the compressed data.

compress_file(input_filename, output_filename): This line calls the compress_file function with the input and output filenames as arguments, which compresses the input file and saves the compressed data to the output file.

#clcoding.com: This line appears to be a comment, possibly indicating the source of the file (clcoding.com). Comments in Python are preceded by the # symbol and are ignored by the interpreter.

This script takes a file (clcoding.txt), compresses it using gzip, and saves the compressed data to a new file (clcoding.txt.gz).


Sunday 5 May 2024

Donut Charts using Python

 


Code:

import matplotlib.pyplot as plt

# Data to plot
labels = ['A', 'B', 'C', 'D']
sizes = [15, 30, 45, 10]

# Plot
plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=140)

# Draw a circle at the center of pie to make it look like a donut
centre_circle = plt.Circle((0,0),0.70,fc='white')
fig = plt.gcf()
fig.gca().add_artist(centre_circle)

# Equal aspect ratio ensures that pie is drawn as a circle
plt.axis('equal')

plt.title('Basic Donut Chart')
plt.show()

#clcoding.com

Explanation:


In this code snippet, we're using the matplotlib.pyplot module, which is a powerful library in Python for creating static, animated, and interactive visualizations. We're importing it using the alias plt, which is a common convention for brevity.

Here's a breakdown of the code:

Importing matplotlib.pyplot: import matplotlib.pyplot as plt
This line imports the matplotlib.pyplot module and assigns it the alias plt, allowing us to reference it with the shorter name plt throughout the code.

labels = ['A', 'B', 'C', 'D']
sizes = [15, 30, 45, 10]
These lines define the data we want to visualize. labels contains the labels for each segment of the pie chart, and sizes contains the corresponding sizes or values for each segment.
Plotting the pie chart:

plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=140)
Here, we use the plt.pie() function to create a pie chart. We pass sizes as the data to plot, labels to label each segment, autopct='%1.1f%%' to display the percentage for each segment, and startangle=140 to rotate the pie chart to start from the angle 140 degrees.
Drawing a circle to create a donut effect:

centre_circle = plt.Circle((0,0),0.70,fc='white')
fig = plt.gcf()
fig.gca().add_artist(centre_circle)
These lines draw a white circle at the center of the pie chart, creating a donut-like appearance. The plt.Circle() function creates a circle with the specified parameters: center (0,0) and radius 0.70.
Setting equal aspect ratio:

plt.axis('equal')
This line ensures that the plot is displayed with equal aspect ratio, so the pie chart appears as a circle rather than an ellipse.
Adding a title and displaying the plot:

plt.title('Basic Donut Chart')
plt.show()
Here, we set the title of the plot to 'Basic Donut Chart' using plt.title(), and then plt.show() displays the plot on the screen.
This code generates a basic donut chart with four segments labeled A, B, C, and D, where the size of each segment is determined by the values in the sizes list.



Code:

import matplotlib.pyplot as plt

# Data to plot
labels = ['A', 'B', 'C', 'D']
sizes = [15, 30, 45, 10]
explode = (0, 0.1, 0, 0)  # only "explode" the 2nd slice

# Plot
plt.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%', startangle=140)

# Draw a circle at the center of pie to make it look like a donut
centre_circle = plt.Circle((0,0),0.70,fc='white')
fig = plt.gcf()
fig.gca().add_artist(centre_circle)

# Equal aspect ratio ensures that pie is drawn as a circle
plt.axis('equal')

plt.title('Donut Chart with Exploded Slices')
plt.show()

#clcoding.com

Explanation: 

This code snippet is similar to the previous one, but it adds exploding effect to one of the slices in the pie chart. Let's break down the code:

Importing matplotlib.pyplot:

import matplotlib.pyplot as plt
This line imports the matplotlib.pyplot module and assigns it the alias plt, allowing us to reference it with the shorter name plt throughout the code.
Data to plot:

labels = ['A', 'B', 'C', 'D']
sizes = [15, 30, 45, 10]
explode = (0, 0.1, 0, 0)  # only "explode" the 2nd slice
Here, labels contains the labels for each segment of the pie chart, sizes contains the corresponding sizes or values for each segment, and explode contains the magnitude of the explosion for each slice. In this case, we're exploding the second slice ('B') by 0.1.
Plotting the pie chart:

plt.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%', startangle=140)
This line creates a pie chart using plt.pie(). The explode parameter is used to specify the amount by which to explode each slice. Here, we're exploding only the second slice ('B') by 0.1. Other parameters are similar to the previous example.
Drawing a circle to create a donut effect:

centre_circle = plt.Circle((0,0),0.70,fc='white')
fig = plt.gcf()
fig.gca().add_artist(centre_circle)
This part is the same as before. It draws a white circle at the center of the pie chart, creating a donut-like appearance.
Setting equal aspect ratio:

plt.axis('equal')
This line ensures that the plot is displayed with an equal aspect ratio, so the pie chart appears as a circle.
Adding a title and displaying the plot:

plt.title('Donut Chart with Exploded Slices')
plt.show()
Here, we set the title of the plot to 'Donut Chart with Exploded Slices' and then display the plot.
This code generates a donut chart with four segments labeled A, B, C, and D, where the second slice ('B') is exploded outwards. The size of each segment is determined by the values in the sizes list.




Code:

import matplotlib.pyplot as plt

# Data to plot
labels = ['A', 'B', 'C', 'D']
sizes1 = [25, 30, 35, 10]
sizes2 = [20, 40, 20, 20]

# Plot
fig, ax = plt.subplots()
ax.pie(sizes1, radius=1.2, labels=labels, autopct='%1.1f%%', startangle=140)
ax.pie(sizes2, radius=1, startangle=140, colors=['red', 'green', 'blue', 'yellow'])

# Draw a circle at the center of pie to make it look like a donut
centre_circle = plt.Circle((0,0),0.8,fc='white')
fig = plt.gcf()
fig.gca().add_artist(centre_circle)

# Equal aspect ratio ensures that pie is drawn as a circle
ax.set(aspect="equal")
plt.title('Donut Chart with Multiple Rings')
plt.show()

#clcoding.com

Explanation: 

This code snippet creates a donut chart with multiple rings, demonstrating the capability to display more than one dataset in the same chart. Let's dissect the code:

Importing matplotlib.pyplot:

import matplotlib.pyplot as plt
This line imports the matplotlib.pyplot module and assigns it the alias plt.
Data to plot:

labels = ['A', 'B', 'C', 'D']
sizes1 = [25, 30, 35, 10]
sizes2 = [20, 40, 20, 20]
Two sets of data are defined here: sizes1 and sizes2. Each set represents the values for different rings of the donut chart.
Plotting the donut chart:

fig, ax = plt.subplots()
ax.pie(sizes1, radius=1.2, labels=labels, autopct='%1.1f%%', startangle=140)
ax.pie(sizes2, radius=1, startangle=140, colors=['red', 'green', 'blue', 'yellow'])
This code creates a subplot (fig, ax = plt.subplots()) and then plots two pie charts on the same subplot using ax.pie().
The first ax.pie() call plots the outer ring (sizes1) with a larger radius (radius=1.2), while the second call plots the inner ring (sizes2) with a smaller radius (radius=1).
labels, autopct, and startangle parameters are used to configure the appearance of the pie charts.
Different colors are specified for the inner ring using the colors parameter.
Drawing a circle to create a donut effect:

centre_circle = plt.Circle((0,0),0.8,fc='white')
fig = plt.gcf()
fig.gca().add_artist(centre_circle)
This part is similar to previous examples. It draws a white circle at the center of the pie chart to create the donut-like appearance.
Setting equal aspect ratio:

ax.set(aspect="equal")
This line sets the aspect ratio of the subplot to 'equal', ensuring that the pie charts are displayed as circles.
Adding a title and displaying the plot:

plt.title('Donut Chart with Multiple Rings')
plt.show()
Finally, the title of the plot is set to 'Donut Chart with Multiple Rings', and the plot is displayed.
This code generates a donut chart with two rings, each representing different datasets (sizes1 and sizes2). Each ring has its own set of labels and colors, and they are displayed concentrically to create the donut chart effect.


Saturday 27 April 2024

Why Should You Learn Python Programming?

 

Python programming language has been gaining immense popularity in recent years, and for good reason. Whether you're a beginner looking to dive into the world of coding or an experienced developer seeking to expand your skill set, learning Python offers a myriad of benefits and opportunities. In this blog post, we'll explore some compelling reasons why you should consider learning Python.


Simplicity and Readability:

One of Python's most appealing features is its simplicity and readability. With its clean and concise syntax, Python code resembles plain English, making it easy to understand and write. This simplicity not only reduces the time spent on coding but also makes Python an excellent choice for beginners who are just starting their programming journey.

Versatility: Python's versatility is unmatched. It is a general-purpose programming language that can be used for a wide range of applications, including web development, data analysis, artificial intelligence, machine learning, automation, and more. Whether you're building a website, analyzing large datasets, or developing complex algorithms, Python has the tools and libraries to support your endeavors.


Rich Ecosystem of Libraries and Frameworks:

Python boasts a vast ecosystem of libraries and frameworks that streamline development and empower developers to achieve their goals more efficiently. From web frameworks like Django and Flask to data science libraries such as pandas and NumPy, Python offers robust solutions for virtually any task or project. These libraries and frameworks not only accelerate development but also ensure code reliability and maintainability.

High Demand in the Job Market: In today's technology-driven world, Python skills are in high demand across industries. Companies ranging from startups to tech giants rely on Python for a myriad of purposes, including software development, data analysis, and machine learning. By learning Python, you enhance your employability and open doors to exciting career opportunities in fields such as software engineering, data science, artificial intelligence, and more.

Thriving Community and Resources: Python has a vibrant and supportive community of developers, enthusiasts, and experts who are eager to share knowledge, collaborate on projects, and provide assistance. Whether you're seeking guidance on a coding challenge, looking for tutorials and documentation, or simply connecting with like-minded individuals, the Python community offers a wealth of resources and support networks to help you succeed.

Cross-Platform Compatibility: Python is a cross-platform language, meaning that code written in Python can run seamlessly on various operating systems, including Windows, macOS, and Linux. This cross-platform compatibility ensures that your Python applications can reach a broader audience and be deployed across different environments without major modifications.

In conclusion, learning Python programming offers a multitude of benefits and opportunities for both beginners and experienced developers alike. Its simplicity, versatility, rich ecosystem, high demand in the job market, thriving community, and cross-platform compatibility make it a valuable skill worth acquiring. Whether you're interested in building web applications, analyzing data, or delving into the realms of artificial intelligence and machine learning, Python provides the tools and resources to turn your ideas into reality. So why wait? Start your Python journey today and unlock a world of endless possibilities.


Free Course: Programming for Everybody (Getting Started with Python)

Friday 26 April 2024

Book Giveaway ! One Book one Person

 


  1. Software Architecture Patterns for Serverless Systems - Second Edition: Architecting for innovation with event-driven microservices and micro frontends
  2. Modern C++ Programming Cookbook - Third Edition: Master modern C++ including the latest features of C++23 with 140+ practical recipes
  3. Build your own Programming Language - Second Edition: A developer's comprehensive guide to crafting, compiling, and implementing programming languages
  4. Unity Cookbook - Fifth Edition: Over 160 recipes to craft your own masterpiece in Unity 2023
  5. Deep Learning Illustrated: A Visual, Interactive Guide to Artificial Intelligence (Addison-Wesley Data & Analytics Series)
  6. Terraform Cookbook - Second Edition: Provision, run, and scale cloud architecture with real-world examples using Terraform
  7. Dancing with Qubits - Second Edition: From qubits to algorithms, embark on the quantum computing journey shaping our future
  8. Interpretable Machine Learning with Python - Second Edition: Build explainable, fair, and robust high-performance models with hands-on, real-world examples
  9. Generative AI with LangChain: Build large language model (LLM) apps with Python, ChatGPT and other LLMs
  10. Transformers for Natural Language Processing and Computer Vision - Third Edition: Explore Generative AI and Large Language Models with Hugging Face, ChatGPT, GPT-4V, and DALL-E 3
  11. Java Coding Problems - Second Edition: Become an expert Java programmer by solving over 250 brand-new, modern, real-world problems
  12. Azure Data Factory Cookbook - Second Edition: A data engineer's guide to building and managing ETL and ELT pipelines with data integration
  13. Systems Engineering Demystified - Second Edition: Apply modern, model-based systems engineering techniques to build complex systems
  14. Extending Power BI with Python and R - Second Edition: Perform advanced analysis using the power of analytical languages
  15. 50 Algorithms Every Programmer Should Know - Second Edition: An unbeatable arsenal of algorithmic solutions for real-world problems
  16. Python for Security and Networking - Third Edition: Leverage Python modules and tools in securing your network and applications
  17. Developing Kaggle Notebooks: Pave your way to becoming a Kaggle Notebooks Grandmaster
  18. Machine Learning Engineering with Python - Second Edition: Manage the lifecycle of machine learning models using MLOps with practical examples
  19. Generative AI with Python and TensorFlow 2: Create images, text, and music with VAEs, GANs, LSTMs, Transformer models
  20. Functional Python Programming - Third Edition: Use a functional approach to write succinct, expressive, and efficient Python code
  21. Mastering Go - Fourth Edition: Leverage Go's expertise for advanced utilities, empowering you to develop professional software


Wednesday 24 April 2024

Calculate Integration using Python

 

# Define an exponential function
h = sp.exp(x)

# Compute the indefinite integral
H = sp.integrate(h, x)

print("∫exp(x) dx =", H)

#clcoding.com
import sympy as sp

# Define the variable and function
x = sp.Symbol('x')
f = x**2 + 3*x + 2

# Compute the indefinite integral
F = sp.integrate(f, x)

print("∫f(x) dx =", F)

#clcoding.com 
# Define the range and compute the definite integral
a = 0
b = 1
integral_value = sp.integrate(f, (x, a, b))

print("∫f(x) dx from", a, "to", b, "=", integral_value)

#clcoding.com
# Define a trigonometric function
g = sp.sin(x)

# Compute the indefinite integral
G = sp.integrate(g, x)

print("∫sin(x) dx =", G)

#clcoding.com

Tuesday 23 April 2024

Taming Data with Tuples



Creating Tuples:

You can create a tuple by enclosing a sequence of elements within parentheses ().


tuple1 = (1, 2, 3)

tuple2 = ('a', 'b', 'c')

mixed_tuple = (1, 'hello', 3.14)


#clcoding.com 

Accessing Elements:

You can access elements of a tuple using indexing, just like with lists.


tuple1 = (1, 2, 3)

print(tuple1[0])  

print(tuple1[1])  


#clcoding.com 

1

2

Iterating over Tuples:

You can iterate over the elements of a tuple using a loop.

tuple1 = ('apple', 'banana', 'cherry')
for fruit in tuple1:
    print(fruit)
    
#clcoding.com
apple
banana
cherry

Tuple Methods:

Tuples have only two built-in methods: count() and index().

tuple1 = (1, 2, 2, 3, 4, 2)
print(tuple1.count(2))  # Output: 3
print(tuple1.index(3))  # Output: 3

#clcoding.com
3
3


Immutable Nature:

Once a tuple is created, you cannot modify its elements.


tuple1 = (1, 2, 3)

# This will raise an error

tuple1[0] = 4


#clcoding.com

Tuple Unpacking:

You can unpack a tuple into individual variables.


tuple1 = ('apple', 'banana', 'cherry')

a, b, c = tuple1

print(a)  

print(b)  

print(c)  


#clcoding.com

apple

banana

cherry


Returning Multiple Values from Functions:

Functions in Python can return tuples, allowing you to return multiple values.


def get_coordinates():

    x = 10

    y = 20

    return x, y


x_coord, y_coord = get_coordinates()

print("x coordinate:", x_coord)  

print("y coordinate:", y_coord)  


#clcoding.com

x coordinate: 10

y coordinate: 20

Iterating over Tuples:

You can iterate over the elements of a tuple using a loop.


tuple1 = ('apple', 'banana', 'cherry')

for fruit in tuple1:

    print(fruit)

    

#clcoding.com

apple

banana

cherry

Sorting Algorithms using Python

 

Code:

def selection_sort(arr):

    n = len(arr)

    for i in range(n):

        min_idx = i

        for j in range(i+1, n):

            if arr[j] < arr[min_idx]:

                min_idx = j

        arr[i], arr[min_idx] = arr[min_idx], arr[i]

    return arr


# Example usage:

arr = [64, 34, 25, 12, 22, 11, 90]

print("Original array:", arr)

sorted_arr = selection_sort(arr)

print("Sorted array:", sorted_arr)


#clcoding.com

Explanation: 

The selection_sort function sorts a given array arr in ascending order using the selection sort algorithm. Here's how it works:

Initialization:
Get the length of the array arr and store it in the variable n.
Outer Loop:
Iterate over each element of the array from index 0 to n-1.
For each iteration, consider the current element as the minimum (min_idx).
Inner Loop:
Within each outer loop iteration, iterate over the unsorted part of the array from index i+1 to n-1.
Find the index of the minimum element (min_idx) among the unsorted elements.
Swap:
After finding the minimum element in the unsorted part, swap it with the element at index i, which is the first element of the unsorted part.
Repeat:
Repeat steps 2-4 until the entire array is sorted.
Return Sorted Array:
Return the sorted array arr.
Now, let's walk through the provided example:

arr = [64, 34, 25, 12, 22, 11, 90]
We start with the original array [64, 34, 25, 12, 22, 11, 90].

sorted_arr = selection_sort(arr)
We call the selection_sort function with the array arr and store the sorted array in sorted_arr.

print("Sorted array:", sorted_arr)
We print the sorted array.
Output:

Original array: [64, 34, 25, 12, 22, 11, 90]
Sorted array: [11, 12, 22, 25, 34, 64, 90]
The original array is [64, 34, 25, 12, 22, 11, 90].
After sorting, the array becomes [11, 12, 22, 25, 34, 64, 90], which is printed as the sorted array.

Code:

def quick_sort(arr):

    if len(arr) <= 1:

        return arr

    pivot = arr[len(arr) // 2]

    left = [x for x in arr if x < pivot]

    middle = [x for x in arr if x == pivot]

    right = [x for x in arr if x > pivot]

    return quick_sort(left) + middle + quick_sort(right)


# Example usage:

arr = [64, 34, 25, 12, 22, 11, 90]

print("Original array:", arr)

sorted_arr = quick_sort(arr)

print("Sorted array:", sorted_arr)


#clcoding.com

Explanation: 

The quick_sort function implements the quicksort algorithm, a popular sorting algorithm known for its efficiency. Here's how it works:

Base Case:

If the length of the input array arr is 0 or 1, it is already sorted, so we return the array as is.

Pivot Selection:

Choose a pivot element from the array. In this implementation, the pivot is selected as the element at the middle index (len(arr) // 2).

Partitioning:

Partition the array into three sub-arrays:

left: Contains elements less than the pivot.

middle: Contains elements equal to the pivot.

right: Contains elements greater than the pivot.

Recursion:

Recursively apply the quicksort algorithm to the left and right sub-arrays.

Combine:

Concatenate the sorted left, middle, and right sub-arrays to form the sorted array.

Now, let's walk through the provided example:

arr = [64, 34, 25, 12, 22, 11, 90]

We start with the original array [64, 34, 25, 12, 22, 11, 90].

sorted_arr = quick_sort(arr)

We call the quick_sort function with the array arr and store the sorted array in sorted_arr.

print("Sorted array:", sorted_arr)

We print the sorted array.

Output:

Original array: [64, 34, 25, 12, 22, 11, 90]

Sorted array: [11, 12, 22, 25, 34, 64, 90]

The original array is [64, 34, 25, 12, 22, 11, 90].

After sorting, the array becomes [11, 12, 22, 25, 34, 64, 90], which is printed as the sorted array.

Code:

def bubble_sort(arr):

    n = len(arr)

    for i in range(n):

        for j in range(0, n-i-1):

            if arr[j] > arr[j+1]:

                arr[j], arr[j+1] = arr[j+1], arr[j]

    return arr

# Example usage:

arr = [64, 34, 25, 12, 22, 11, 90]

print("Original array:", arr)

sorted_arr = bubble_sort(arr)

print("Sorted array:", sorted_arr)


#clcoding.com

Explanation:

The bubble_sort function implements the bubble sort algorithm, which repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. Here's how it works:

Iteration:
The outer loop iterates through the entire array arr.
Each iteration (i) represents one pass through the array.
Comparison and Swapping:
The inner loop iterates from index 0 to n - i - 1.
Within each inner loop iteration (j), adjacent elements arr[j] and arr[j+1] are compared.
If arr[j] is greater than arr[j+1], they are swapped.
Largest Element Bubbles Up:
With each pass of the outer loop, the largest element in the unsorted part of the array "bubbles up" to its correct position at the end of the array.
Repeat Until Sorted:
Repeat steps 1-3 until the entire array is sorted.
Now, let's walk through the provided example:

arr = [64, 34, 25, 12, 22, 11, 90]
We start with the original array [64, 34, 25, 12, 22, 11, 90].

sorted_arr = bubble_sort(arr)
We call the bubble_sort function with the array arr and store the sorted array in sorted_arr.

print("Sorted array:", sorted_arr)
We print the sorted array.
Output:

Original array: [64, 34, 25, 12, 22, 11, 90]
Sorted array: [11, 12, 22, 25, 34, 64, 90]
The original array is [64, 34, 25, 12, 22, 11, 90].
After sorting, the array becomes [11, 12, 22, 25, 34, 64, 90], which is printed as the sorted array.


Code:

def insertion_sort(arr):

    for i in range(1, len(arr)):

        key = arr[i]

        j = i - 1

        while j >= 0 and key < arr[j]:

            arr[j + 1] = arr[j]

            j -= 1

        arr[j + 1] = key

    return arr


# Example usage:

arr = [64, 34, 25, 12, 22, 11, 90]

print("Original array:", arr)

sorted_arr = insertion_sort(arr)

print("Sorted array:", sorted_arr)


#clcoding.com

Explanation:

The insertion_sort function implements the insertion sort algorithm, which builds the final sorted array one element at a time by repeatedly moving elements that are out of order. Here's how it works:

Iteration:
The outer loop iterates over the array arr, starting from index 1.
Each iteration (i) considers one element at a time, starting from the second element.
Key Selection:
Within each iteration, the current element (arr[i]) is selected as the key to be inserted into the sorted sub-array.
Comparison and Shifting:
The inner loop (while loop) compares the key with the elements in the sorted sub-array (elements before arr[i]).
Elements greater than the key are shifted one position to the right to make space for the key.
This shifting continues until an element less than or equal to the key is found, or until the beginning of the array is reached (j < 0).
Insertion:
Once the correct position for the key is found, it is inserted into the sorted sub-array at index j + 1.
Repeat Until Sorted:
Repeat steps 1-4 until the entire array is sorted.
Now, let's walk through the provided example:

arr = [64, 34, 25, 12, 22, 11, 90]
We start with the original array [64, 34, 25, 12, 22, 11, 90].

sorted_arr = insertion_sort(arr)
We call the insertion_sort function with the array arr and store the sorted array in sorted_arr.

print("Sorted array:", sorted_arr)
We print the sorted array.
Output:

Original array: [64, 34, 25, 12, 22, 11, 90]
Sorted array: [11, 12, 22, 25, 34, 64, 90]
The original array is [64, 34, 25, 12, 22, 11, 90].
After sorting, the array becomes [11, 12, 22, 25, 34, 64, 90], which is printed as the sorted array.






Sunday 21 April 2024

Python Program to find info about Chemical Formula

 

import pubchempy as pcp

# Take name as input

chemical_name = input("Enter chemical name: ")

try:

    # Search PubChem for the compound by its name

    compound = pcp.get_compounds(chemical_name, 'name')[0]

    # Display information about the compound

    print(f"IUPAC Name: {compound.iupac_name}")

    print(f"Common Name: {compound.synonyms[0]}")

    print(f"Molecular Weight: {compound.molecular_weight}")

    print(f"Formula: {compound.molecular_formula}")

    # You can access more properties as needed

except IndexError:

    print(f"No information found for {chemical_name}.")

    #clcoding.com

Explanation: 

This code snippet performs a similar task to the previous one but takes the name of a chemical compound as input instead of its chemical formula. Here's an explanation of each part:

import pubchempy as pcp: This line imports the PubChemPy library and aliases it as pcp, allowing us to refer to it more conveniently in the code.

chemical_name = input("Enter chemical name: "): This line prompts the user to input the name of the chemical compound they want to retrieve information about. The input is stored in the variable chemical_name.

try:: This starts a try-except block, indicating that we are going to try a piece of code that might raise an exception, and if it does, we'll handle it gracefully.

compound = pcp.get_compounds(chemical_name, 'name')[0]: This line uses the get_compounds function from the PubChemPy library to search for compounds matching the provided chemical name. The function takes two arguments: the chemical name (chemical_name) and a string indicating that we are searching by name ('name'). Since get_compounds returns a list of compounds, we select the first compound using [0] and assign it to the variable compound.

Printing compound information:

print(f"IUPAC Name: {compound.iupac_name}"): This line prints the IUPAC (International Union of Pure and Applied Chemistry) name of the compound.

print(f"Common Name: {compound.synonyms[0]}"): This line prints the common name of the compound, using the first synonym available.

print(f"Molecular Weight: {compound.molecular_weight}"): This line prints the molecular weight of the compound.

print(f"Formula: {compound.molecular_formula}"): This line prints the molecular formula of the compound.

except IndexError:: This block catches the IndexError exception, which occurs if no compound is found for the provided chemical name.

print(f"No information found for {chemical_name}."): If an IndexError occurs, this line prints a message indicating that no information was found for the provided chemical name.

In summary, this code allows the user to input the name of a chemical compound, searches for the corresponding compound in the PubChem database using PubChemPy, and displays information about the compound if found. If no information is found for the provided name, it prints a corresponding message.


import pubchempy as pcp

# Define the chemical formula 

chemical_formula = input("Enter chemical Formula : ")  

try:

    # Search PubChem for the compound by its chemical formula

    compound = pcp.get_compounds(chemical_formula, 'formula')[0]

    # Display information about the compound

    print(f"IUPAC Name: {compound.iupac_name}")

    print(f"Common Name: {compound.synonyms[0]}")

    print(f"Molecular Weight: {compound.molecular_weight}")

    print(f"Formula: {compound.molecular_formula}")

    # You can access more properties as needed

except IndexError:

    print(f"No information found for {chemical_formula}.")

    #clcoding.com

Explantion:

This code snippet aims to retrieve information about a chemical compound using its chemical formula. Here's a breakdown of each part:

import pubchempy as pcp: This line imports the PubChemPy library and aliases it as pcp, allowing us to refer to it more conveniently in the code. PubChemPy is a Python library for accessing chemical information from the PubChem database.

chemical_formula = input("Enter chemical Formula : "): This line prompts the user to input the chemical formula of the compound they want to retrieve information about. The input is stored in the variable chemical_formula.

try:: This starts a try-except block, indicating that we are going to try a piece of code that might raise an exception, and if it does, we'll handle it gracefully.

compound = pcp.get_compounds(chemical_formula, 'formula')[0]: This line uses the get_compounds function from the PubChemPy library to search for compounds matching the provided chemical formula. The function takes two arguments: the chemical formula (chemical_formula) and a string indicating that we are searching by formula ('formula'). Since get_compounds returns a list of compounds, we select the first compound using [0] and assign it to the variable compound.

Printing compound information:

print(f"IUPAC Name: {compound.iupac_name}"): This line prints the IUPAC (International Union of Pure and Applied Chemistry) name of the compound.

print(f"Common Name: {compound.synonyms[0]}"): This line prints the common name of the compound, using the first synonym available.

print(f"Molecular Weight: {compound.molecular_weight}"): This line prints the molecular weight of the compound.

print(f"Formula: {compound.molecular_formula}"): This line prints the molecular formula of the compound.

except IndexError:: This block catches the IndexError exception, which occurs if no compound is found for the provided chemical formula.

print(f"No information found for {chemical_formula}."): If an IndexError occurs, this line prints a message indicating that no information was found for the provided chemical formula.

In summary, this code allows the user to input a chemical formula, searches for the corresponding compound in the PubChem database using PubChemPy, and displays information about the compound if found. If no information is found for the provided formula, it prints a corresponding message.

Tuesday 16 April 2024

Element information using Python

 

Code:

import periodictable


# Function to get information about an element

def get_element_info(symbol):

    # Check if the symbol is valid

    if not periodictable.elements.symbol(symbol):

        print("Invalid element symbol.")

        return    

    # Access information about the specified element

    element = periodictable.elements.symbol(symbol)

    

    # Print information about the element

    print(f"Element: {element.name}")

    print(f"Symbol: {element.symbol}")

    print(f"Atomic Number: {element.number}")

    print(f"Atomic Weight: {element.mass}")

    print(f"Density: {element.density}")

    

# Prompt the user to input an element symbol

element_symbol = input("Enter the symbol of the element: ")


# Call the function to get information about the specified element

get_element_info(element_symbol)


#clcoding.com

Explanation:

The line import periodictable imports a Python library/module named "periodictable". This library provides information about chemical elements such as their names, symbols, atomic numbers, atomic weights, and other properties.

In the provided code:

get_element_info(symbol) is a function that takes an element symbol as input and retrieves information about that element.
if not periodictable.elements.symbol(symbol): checks if the symbol entered by the user is valid. If it's not valid, it prints "Invalid element symbol." and exits the function.
element = periodictable.elements.symbol(symbol) accesses the information about the specified element using the symbol() method provided by the periodictable library.
Information about the element, such as its name, symbol, atomic number, atomic weight, and density (if available), is then printed using print statements.
The code prompts the user to input an element symbol, then calls the get_element_info function to display information about the specified element. If the element symbol provided by the user is not valid, it informs the user about the invalid input.

Monday 15 April 2024

Automatically Generate Image CAPTCHAs with Python for Enhanced Security

 

Code:

from captcha.image import ImageCaptcha 

import random

# Specify the image size

image = ImageCaptcha(width=450, height=100)

# Generate random captcha text

def generate_random_captcha_text(length=6):

    characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'

    captcha_text = ''.join(random.choice(characters) for _ in range(length))

    return captcha_text


# Get random captcha text

captcha_text = generate_random_captcha_text()


# Generate the image of the given text

data = image.generate(captcha_text)


# Write the image on the given file and save it

image.write(captcha_text, 'CAPTCHA1.png')


from PIL import Image

Image.open('CAPTCHA1.png')


#clcoding.com


Explanation: 

This code snippet demonstrates how to automatically generate an image CAPTCHA using Python. Here's a breakdown of each part:

from captcha.image import ImageCaptcha: This imports the ImageCaptcha class from the captcha.image module. This class allows you to create CAPTCHA images.

import random: This imports the random module, which is used to generate random characters for the CAPTCHA text.

image = ImageCaptcha(width=450, height=100): This initializes an instance of the ImageCaptcha class with the specified width and height for the CAPTCHA image.

generate_random_captcha_text(length=6): This is a function that generates random CAPTCHA text. It takes an optional parameter length, which specifies the length of the CAPTCHA text. By default, it generates a text of length 6.

captcha_text = generate_random_captcha_text(): This calls the generate_random_captcha_text function to generate random CAPTCHA text and assigns it to the variable captcha_text.

data = image.generate(captcha_text): This generates the CAPTCHA image using the generated text. It returns the image data.

image.write(captcha_text, 'CAPTCHA1.png'): This writes the generated CAPTCHA image to a file named "CAPTCHA1.png" with the text embedded in the image.

from PIL import Image: This imports the Image class from the Python Imaging Library (PIL) module, which is used to open and display the generated CAPTCHA image.

Image.open('CAPTCHA1.png'): This opens the generated CAPTCHA image named "CAPTCHA1.png" using the PIL library.

Overall, this code generates a random CAPTCHA text, creates an image of the text using the ImageCaptcha class, saves the image to a file, and then displays the image using PIL.

Saturday 13 April 2024

Remove Image Background using Python

 

from rembg import remove

from PIL import Image

input_path = 'p22.jpg'

output_path = 'p22.png'

inp = Image.open(input_path)

output = remove(inp)

output.save(output_path)

#clcoding.com

Explanantion: 

This code snippet appears to be a Python script using the rembg library to remove the background from an image. Let me break it down for you:

from rembg import remove: This line imports the remove function from the rembg library. rembg is likely a library designed for background removal from images.

from PIL import Image: This line imports the Image module from the Python Imaging Library (PIL). PIL is used for opening, manipulating, and saving many different image file formats.

input_path = 'p22.jpg': This line sets the path to the input image file named "p22.jpg". This is the image from which we want to remove the background.

output_path = 'p22.png': This line sets the path for the output image file named "p22.png". The background-removed image will be saved with this filename and format (PNG).

inp = Image.open(input_path): This line opens the input image file using PIL's Image.open() function and assigns it to the variable inp. Now inp holds the image object.

output = remove(inp): This line calls the remove() function from the rembg library and passes the input image (inp) as an argument. This function is expected to perform the background removal operation on the input image.

output.save(output_path): This line saves the background-removed image (output) to the specified output path (output_path). It's saved in PNG format due to the extension provided in the output_path.

The comments at the end (#clcoding.com) seem to indicate the source or reference of the code, possibly a website or a tutorial where this code was found.






Python library to filter and censor offensive language

 

from better_profanity import profanity

text = "What the hell is going on?"

censored_text = profanity.censor(text)

print(censored_text)  


#clcoding.com

Explanation: 

The line from better_profanity import profanity imports the profanity module from the better_profanity library. This module provides functions and utilities for filtering and censoring offensive language in text.

Here's a breakdown of the subsequent code:

text = "What the hell is going on?": This line assigns a string containing a sentence to the variable text. The sentence includes the word "hell," which is considered offensive.

censored_text = profanity.censor(text): This line uses the censor function from the profanity module to censor any profanity in the text variable. The function replaces offensive words with asterisks (*) or other censor characters.

print(censored_text): This line prints the censored version of the text to the console. In this case, since "hell" is considered offensive, it will be replaced with asterisks, resulting in a censored version of the original sentence.

So, the output of this code will be a censored version of the original text, where the offensive word "hell" is replaced with asterisks.


from better_profanity import profanity

text = "I can't believe he said that!"

has_profanity = profanity.contains_profanity(text)

print(has_profanity) 


#clcoding.com

Explanation:

The line from better_profanity import profanity imports the profanity module from the better_profanity library. This module provides functions and utilities for filtering and detecting offensive language in text.

Here's a breakdown of the subsequent code:

text = "I can't believe he said that!": This line assigns a string containing a sentence to the variable text. The sentence does not contain any explicit profanity.

has_profanity = profanity.contains_profanity(text): This line calls the contains_profanity function from the profanity module and passes the text variable as an argument. This function checks whether the provided text contains any profanity.

print(has_profanity): This line prints the result of the profanity check to the console. If the text contains any profanity, the result will be True; otherwise, it will be False.

After executing this code, the result printed to the console will indicate whether the provided text contains any profanity. Since the text "I can't believe he said that!" does not contain explicit profanity, the output will be False.



from better_profanity import profanity
custom_censor_words = ["heck", "darn", "frick"]
censor_word = profanity.load_censor_words(custom_censor_words)

#clcoding.com

Explanation:

The line from better_profanity import profanity imports the profanity module from the better_profanity library. This module provides functions and utilities for filtering and censoring offensive language in text.

Here's an explanation of the subsequent code:

custom_censor_words = ["heck", "darn", "frick"]: This line creates a list named custom_censor_words containing custom words that you want to be treated as profanity and censored.

censor_word = profanity.load_censor_words(custom_censor_words): This line calls the load_censor_words function from the profanity module and passes the custom_censor_words list as an argument. This function loads the custom censor words into the profanity filter.

However, there's a small correction here: The load_censor_words function doesn't return anything (None), so assigning its result to censor_word doesn't serve any purpose. It's primarily used to load the custom censor words into the profanity filter.

After executing this code, the profanity filter will include the custom censor words provided in the custom_censor_words list. Any occurrence of these words in the text will be censored according to the filter's settings.

Popular Posts

Categories

AI (31) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (146) C (77) C# (12) C++ (82) Course (67) Coursera (198) Cybersecurity (24) data management (11) Data Science (106) Data Strucures (8) Deep Learning (13) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (20) Hadoop (3) HTML&CSS (47) IBM (25) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (46) Meta (18) MICHIGAN (5) microsoft (4) Nvidia (1) Pandas (3) PHP (20) Projects (29) Python (882) Python Coding Challenge (281) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (42) UX Research (1) web application (8)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses