Monday 19 August 2024

8 Levels of Writing Python Functions

 Level 1: Basic Function Definition

Goal: Learn how to define simple functions with def.


def greet():

    return "Hello, World!"

Concepts: Function definition, return statement, and basic usage.


Level 2: Function Arguments

Goal: Understand how to pass data to functions using arguments.


def greet(name):

    return f"Hello, {name}!"

Concepts: Positional arguments, basic string formatting.


Level 3: Default Arguments

Goal: Use default argument values to make functions more flexible.

def greet(name="World"):

    return f"Hello, {name}!"

Concepts: Default values, handling optional parameters.


Level 4: Variable-Length Arguments

Goal: Handle an arbitrary number of arguments using args and *kwargs.


def greet(*names):

    return "Hello, " + ", ".join(names) + "!"

Concepts: args for positional arguments, *kwargs for keyword arguments.


Level 5: Return Multiple Values

Goal: Return multiple values from a function using tuples.

def divide(a, b):

    quotient = a // b

    remainder = a % b

    return quotient, remainder

    

Concepts: Tuple unpacking, returning multiple values.


Level 6: First-Class Functions

Goal: Treat functions as first-class citizens by passing them as arguments or returning them.


def apply_function(func, value):

    return func(value)


def square(x):

    return x * x


result = apply_function(square, 5)

Concepts: Functions as arguments, higher-order functions.


Level 7: Lambda Functions

Goal: Use lambda expressions for short, unnamed functions.


def apply_function(func, value):

    return func(value)


result = apply_function(lambda x: x * x, 5)

Concepts: Lambda expressions, anonymous functions.


Level 8: Decorators

Goal: Modify the behavior of functions using decorators.

def decorator(func):

    def wrapper(*args, **kwargs):

        print("Before the function")

        result = func(*args, **kwargs)

        print("After the function")

        return result

    return wrapper


@decorator

def greet(name):

    return f"Hello, {name}!"


greet("World")

Before the function

After the function

'Hello, World!'

Concepts: Decorators, wrapping functions, modifying behavior.

Sunday 18 August 2024

Pencil Sketch using Python

 

import cv2

import numpy as np


def pencil_sketch(image_path, output_path):

    image = cv2.imread(image_path)


    gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)


    inverted_gray_image = cv2.bitwise_not(gray_image)


    blurred_image = cv2.GaussianBlur(inverted_gray_image, (21, 21), 0)


    inverted_blurred_image = cv2.bitwise_not(blurred_image)

    pencil_sketch_image = cv2.divide(gray_image, inverted_blurred_image, scale=256.0)

    cv2.imwrite(output_path, pencil_sketch_image)

 

    cv2.imshow('Pencil Sketch', pencil_sketch_image)

    cv2.waitKey(0)

    cv2.destroyAllWindows()


input_image_path = 'w2.jpg'

output_image_path = 'w2_sketch.jpg'

pencil_sketch(input_image_path, output_image_path)

World map using Python

 

pip install cartopy


import cartopy.crs as ccrs

import cartopy.feature as cfeature

import matplotlib.pyplot as plt


projection = ccrs.PlateCarree()


fig, ax = plt.subplots(subplot_kw={'projection': projection})

ax.set_extent([-180, 180, -90, 90], crs=ccrs.PlateCarree())


ax.add_feature(cfeature.LAND, facecolor='lightgray')

ax.add_feature(cfeature.OCEAN, facecolor='lightblue')


ax.gridlines()

plt.show()


Movie Information using Python

 

import imdb


ia = imdb.Cinemagoer()

Movie = input("Enter a movie name: ")

items = ia.search_movie(Movie)

print("\nSearch results:")

for index, movie in enumerate(items):

    print(f"{index + 1}. {movie['title']} ({movie['year']})")


movie_index = int(input("\nEnter the number of the movie you want to get info for: ")) - 1

movie_id = items[movie_index].movieID

movie_info = ia.get_movie(movie_id)


print("\nMovie Information:")

print(f"Title: {movie_info.get('title')}")

print(f"Year: {movie_info.get('year')}")

print(f"Rating: {movie_info.get('rating')}")

print(f"Genres: {', '.join(movie_info.get('genres', []))}")

print(f"Director(s): {', '.join(str(d) for d in movie_info.get('directors', []))}")

print(f"Cast: {', '.join(str(c) for c in movie_info.get('cast', [])[:5])}...") 

print(f"Plot: {movie_info.get('plot outline')}")

print(f"Runtime: {movie_info.get('runtimes', ['N/A'])[0]} minutes")

print(f"Country: {', '.join(movie_info.get('countries', []))}")

print(f"Language: {', '.join(movie_info.get('languages', []))}")


#Source Code --> clcoding.com

Search results:

1. Lift (2024)

2. Elevator to the Gallows (1958)

3. Lift (2021)

4. The Lift (1983)

5. Lift (2001)

6. The Big Lift (1950)

7. Lift (2022)

8. Lift (2016)

9. Lift Off (1992)

10. How Heavy Are the Dumbbells You Lift? (2019)

11. Lift (1989)

12. Lift Me Up (2015)

13. The Lift Boy (2019)

14. Lift (2019)

15. Lift (2017)

16. Lift (2018)

17. The Lift (2022)

18. Lift Off (1969)

19. LIFT (2019)

20. Lift Off (2021)

Movie Information:

Title: Lift

Year: 2024

Rating: 5.5

Genres: Action, Comedy, Crime, Drama, Thriller

Director(s): F. Gary Gray

Cast: Kevin Hart, Gugu Mbatha-Raw, Sam Worthington, Vincent D'Onofrio, Úrsula Corberó...

Plot: Cyrus, an international thief and his crew specialize in stealing extremely costly art pieces and resort to kidnapping if necessary. Cyrus's ex girlfriend Abby, an Interpol agent convinces him to steal a huge consignment of gold being sent by plane from London to Zurich in return for immunity from arrest . Cyrus knows this is an almost impossible task but decides to go ahead since it means freedom for him and his crew not to speak of his getting together with Abby again.

Runtime: 107 minutes

Country: United States

Language: English, Italian

 

Saturday 17 August 2024

Top 5 Python Programs Using demoji for Emoji Processing

 1. Remove Emojis from a Text String

This program removes all emojis from a given text string.


import demoji

text = "Python is fun! 🐍🔥 Let's code! 💻🎉"

cleaned_text = demoji.replace(text, "")

print(cleaned_text)

#source Code --> clcoding.com

Python is fun!  Let's code! 

2. Replace Emojis with Descriptions

This program replaces emojis in a text with their corresponding descriptions.


import demoji

text = "Good morning! ☀️ Have a nice day! 🌸😊"

emojis = demoji.findall(text)

for emoji, description in emojis.items():

    text = text.replace(emoji, f"[{description}]")

print(text)

#source Code --> clcoding.com

Good morning! [sun] Have a nice day! [cherry blossom][smiling face with smiling eyes]

3. Count the Number of Emojis in a Text

This program counts how many emojis are present in a text string.


import demoji

text = "Coding is awesome! 👨‍💻🚀🤓"

emoji_count = len(demoji.findall(text))

print(f"Number of emojis: {emoji_count}")

#source Code --> clcoding.com

Number of emojis: 3

4. Extract All Emojis from a Text

This program extracts all the emojis from a given text string.


import demoji

text = "Enjoy your meal! 🍽️🍕🍔🍟"

emojis = demoji.findall(text)

print("Emojis found:", list(emojis.keys()))

#source Code --> clcoding.com

Emojis found: ['🍕', '🍽️', '🍟', '🍔']

5. Create an Emoji Frequency Dictionary

This program creates a dictionary that maps each emoji in a text to the number of times it appears.


import demoji

text = "I love 🍎 and 🍌. Do you like 🍎 too? 🍎🍎"

emoji_freq = {}

emojis = demoji.findall(text)

for emoji in emojis.keys():

    emoji_freq[emoji] = text.count(emoji)

print("Emoji Frequency:", emoji_freq)

#source Code --> clcoding.com

Emoji Frequency: {'🍌': 1, '🍎': 4}

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

 

def func(x=[]):

    x.append(1)

    return x

print(func())

print(func())

Solution and Explanation: B is the correct answer

Default Argument Behavior:

The default argument x=[] is evaluated only once when the function is defined, not each time the function is called. This means that if the default value is a mutable object like a list, it will be shared across all calls to the function.

First Function Call (print(func())):

The first time func() is called, the list x is empty because the default value ([]) is used.
Inside the function, 1 is appended to the list, so x becomes [1].
The function returns this list, which is then printed, so the output is:

Second Function Call (print(func())):

The second time func() is called, the same list x from the previous call is used, not a new empty list.
Again, 1 is appended to this list, so x becomes [1, 1].
The function returns this list, which is then printed, so the output is:
[1, 1]

Mutable Default Arguments: In Python, using a mutable object (like a list or dictionary) as a default argument can lead to unexpected behavior because it persists across function calls.
Best Practice: To avoid this, use None as the default value and then initialize the mutable object inside the function if needed.

Friday 16 August 2024

Enhancing Python Scripts with Alive-Progress: 5 Practical Examples

 pip install alive-progress


1. Simple Progress Bar

from alive_progress import alive_bar

import time

items = range(100)

with alive_bar(len(items)) as bar:

    for item in items:

        time.sleep(0.05)  

        bar()

|████████████████████████████████████████| 100/100 [100%] in 5.0s (19.83/s) 

2. Progress Bar with Custom Text

from alive_progress import alive_bar

import time


tasks = ['task1', 'task2', 'task3', 'task4']


with alive_bar(len(tasks), title='Processing Tasks') as bar:

    for task in tasks:

        time.sleep(0.5)  

        bar.text = f'Working on {task}'

        bar()

Processing Tasks |████████████████████████████████████████| 4/4 [100%] in 2.0s (2.00/s) 


3. Nested Progress Bars

from alive_progress import alive_bar

import time

outer_items = range(3)

inner_items = range(5)


with alive_bar(len(outer_items) * len(inner_items), title='Processing') as bar:

    for _ in outer_items:

        for _ in inner_items:

            time.sleep(0.1)  # Simulate work

            bar()

Processing |████████████████████████████████████████| 15/15 [100%] in 1.5s (9.94/s) 



4. Download Simulation with Progress Bar

from alive_progress import alive_bar

import time

file_size = 1024  

chunk_size = 64

with alive_bar(file_size // chunk_size, title='Downloading') as bar:

    for _ in range(0, file_size, chunk_size):

        time.sleep(0.1) 

        bar()

Downloading |████████████████████████████████████████| 16/16 [100%] in 1.6s (9.83/s) 

5. Progress Bar with Percentage and ETA

from alive_progress import alive_bar

import time

total_items = 50

with alive_bar(total_items, title='Processing', 

               spinner='dots_waves', bar='smooth') as bar:

    for _ in range(total_items):

        time.sleep(0.1)  

        bar()

Processing |████████████████████████████████████████| 50/50 [100%] in 5.0s (9.95/s) 

Thursday 15 August 2024

Check Internet Speed using Python

 

pip install speedtest-cli


import speedtest as st


def Speed_Test():

    test = st.Speedtest()

    

    down_speed = test.download()

    down_speed = round(down_speed / 10**6, 2)

    print("Download Speed in Mbps: ", down_speed)

 

    up_speed = test.upload()

    up_speed = round(up_speed / 10**6, 2)

    print("Upload Speed in Mbps: ", up_speed)

    

    ping = test.results.ping

    print("Ping: ", ping)

Speed_Test()


#source code -> clcoding.com

Download Speed in Mbps:  20.57

Upload Speed in Mbps:  18.47

Ping:  26.177

Happy Independence Day India

 

import numpy as np

import matplotlib.pyplot as py

import matplotlib.patches as patch


a = patch.Rectangle((0,1), width=9, height=2, facecolor='#138808', edgecolor='grey')

b = patch.Rectangle((0,3), width=9, height=2, facecolor='#ffffff', edgecolor='grey')

c = patch.Rectangle((0,5), width=9, height=2, facecolor='#FF6103', edgecolor='grey')

m,n = py.subplots()

n.add_patch(a)

n.add_patch(b)

n.add_patch(c)


radius=0.8

py.plot(4.5,4, marker = 'o', markerfacecolor = '#000080', markersize = 9.5)

chakra = py.Circle((4.5, 4), radius, color='#000080', fill=False, linewidth=7)

n.add_artist(chakra)


for i in range(0,24):

   p = 4.5 + radius/2 * np.cos(np.pi*i/9 + np.pi/48)

   q = 4.5 + radius/2 * np.cos(np.pi*i/9 - np.pi/48)

   r = 4 + radius/2 * np.sin(np.pi*i/9 + np.pi/48)

   s = 4 + radius/2 * np.sin(np.pi*i/9 - np.pi/48)

   t = 4.5 + radius * np.cos(np.pi*i/9)

   u = 4 + radius * np.sin(np.pi*i/9)

   n.add_patch(patch.Polygon([[4.5,4], [p,r], [t,u],[q,s]], fill=True, 

                             closed=True, color='#000080'))

py.axis('equal')

py.show() 

#clcoding.com

Saturday 10 August 2024

Definite Integration using Python

 

import sympy as sp


x = sp.Symbol('x')

f = input("Enter the function(in terms of x):")


F_indefinite = sp.integrate(f, x)

print("Indefinite integral ∫f(x) dx =", F_indefinite)


a = float(input("Enter the lower limit of integration: "))

b = float(input("Enter the upper limit of integration: "))


F_definite = sp.integrate(f, (x, a, b))

print(f"Definite integral ∫f(x) dx from {a} to {b} =", F_definite)


#clcoding.com

Indefinite integral ∫f(x) dx = x**3/3 + 3*x

Definite integral ∫f(x) dx from 9.0 to 27.0 = 6372.00000000000

Friday 9 August 2024

5 Hidden Gems in Pandas You Should Start Using Today

1. query() Method for Filtering Data
What it is: The query() method allows you to filter data in a DataFrame using a more readable and concise string-based expression.

Why it's useful: It avoids the verbosity of standard indexing and makes the code more readable, especially for complex conditions.

import pandas as pd

df = pd.DataFrame({'A': [1, 2, 3, 4], 
                   'B': [10, 20, 30, 40]})
result = df.query('A > 2 & B < 40')
print(result)

#clcoding.com
   A   B
2  3  30
2. eval() Method for Efficient Calculations
What it is: The eval() method evaluates a string expression within the context of a DataFrame, allowing for efficient computation.

Why it's useful: It can speed up operations involving arithmetic or logical operations on DataFrame columns, especially with large datasets.

df['C'] = df.eval('A + B')
print(df)

#clcoding.com
   A   B   C
0  1  10  11
1  2  20  22
2  3  30  33
3  4  40  44


3. at and iat for Fast Access
What it is: at and iat are optimized methods for accessing scalar values in a DataFrame.

Why it's useful: These methods are much faster than using .loc[] or .iloc[] for individual cell access, making them ideal for performance-critical code.

value = df.at[2, 'B']  
print(value)
#clcoding.com
30

4. pipe() Method for Method Chaining
What it is: The pipe() method allows you to apply a function or sequence of functions to a DataFrame within a method chain.

Why it's useful: It improves code readability by keeping the DataFrame operations within a single fluent chain.

def add_constant(df, value):
    return df + value

df = df.pipe(add_constant, 10)
print(df)

#clcoding.com
    A   B   C
0  11  20  21
1  12  30  32
2  13  40  43
3  14  50  54
5. explode() for Expanding Lists in Cells
What it is: The explode() method expands a list-like column into separate rows.

Why it's useful: This is particularly useful when working with data that has embedded lists within cells and you need to analyze or visualize each item individually.

df = pd.DataFrame({'A': [1, 2], 
                   'B': [[10, 20, 30], [40, 50]]})
df_exploded = df.explode('B')
print(df_exploded)

#clcoding.com
   A   B
0  1  10
0  1  20
0  1  30
1  2  40
1  2  50



Thursday 8 August 2024

Find Weather using Python

 


pip install beautifulsoup4


import requests

from bs4 import BeautifulSoup


city = input("Enter City Name: ")

city_formatted = city.lower().replace(" ", "-")


url = f"https://www.timeanddate.com/weather/{city_formatted}"

response = requests.get(url)


soup = BeautifulSoup(response.text, 'html.parser')


try:

    temperature = soup.find("div", class_="h2").get_text(strip=True)

    description = soup.find("div", class_="h2").find_next("p").get_text(strip=True)


    print(f"Weather in {city}:")

    print(f"Temperature: {temperature}")

    print(f"Condition: {description}")


except AttributeError:

    print("Please check the city name and try again.")

#clcoding.com

Please check the city name and try again.

 

 

Wednesday 7 August 2024

Find current position of a Planet using Python

 

pip install astropy

from astropy.coordinates import get_body, EarthLocation
from astropy.time import Time

now = Time.now()

location = EarthLocation.of_site('greenwich')

planet_name = input("Enter the name of the planet: ").lower()

planet_position = get_body(planet_name, now, location)

print(f"{planet_name.capitalize()} "
      f"Position: RA = {planet_position.ra}, "
      f"Dec = {planet_position.dec}")

#clcoding.com
Mercury Position: RA = 153.76036137226643 deg, Dec = 6.265761309328344 deg
 

Create a map using Python

 

pip install folium

import folium
from IPython.display import display

map_center = [40.7128, -74.0060]
mymap = folium.Map(location=map_center, zoom_start=12)

folium.Marker(
    [40.7128, -74.0060],  
    popup="New York", 
    icon=folium.Icon(color="blue", icon="info-sign")
).add_to(mymap)

display(mymap)

The above code is used to create and display an interactive map using the folium library in Python, specifically within a Jupyter Notebook environment. Below is a step-by-step explanation of the code:

1. Install the folium library

pip install folium
  • pip install folium: This command installs the folium library, which is used for creating interactive maps with Leaflet.js, a popular JavaScript library for mapping.

2. Import necessary libraries

import folium
from IPython.display import display
  • import folium: This imports the folium library, which allows you to create maps and add various layers and markers to them.
  • from IPython.display import display: This imports the display function from IPython.display, enabling the map to be rendered directly within a Jupyter Notebook.

3. Define the center of the map

map_center = [40.7128, -74.0060]
  • map_center: This variable defines the latitude and longitude coordinates of the center of the map, which in this case is set to New York City (latitude: 40.7128, longitude: -74.0060).

4. Create a folium map object

mymap = folium.Map(location=map_center, zoom_start=12)
  • folium.Map(location=map_center, zoom_start=12): This creates a map centered at the specified location with a zoom level of 12, which gives a city-level view of New York.

5. Add a marker to the map

folium.Marker( 
    [40.7128, -74.0060], 
    popup="New York", 
    icon=folium.Icon(color="blue", icon="info-sign") 
  ).add_to(mymap)
  • folium.Marker([40.7128, -74.0060], popup="New York", 
  • icon=folium.Icon(color="blue", icon="info-sign")): This adds a marker to the map at the specified coordinates (New York City). The marker has a popup label "New York" that appears when the marker is clicked, and the icon is styled with a blue color and an info-sign symbol.
  • .add_to(mymap): This adds the marker to the mymap object.

6. Display the map

display(mymap)
    display(mymap): This displays the map in the Jupyter Notebook.

Summary

This code creates an interactive map centered on New York City, adds a marker with a popup and a custom icon, and displays the map within a Jupyter Notebook.

Sunday 4 August 2024

4 Python Mistakes That Make You Look Like a Beginner (And How to Avoid Them)



 1. Using Mutable Default Arguments

Mistake:


def add_item(item, items=[]):

    items.append(item)

    return items

Problem: Default mutable arguments, like lists or dictionaries, retain changes between function calls, which can lead to unexpected behavior.


Fix:


def add_item(item, items=None):

    if items is None:

        items = []

    items.append(item)

    return items


#clcoding.com



2. Not Using List Comprehensions

Mistake:


result = []

for i in range(10):

    result.append(i * 2)

Problem: This approach is verbose and less efficient than it could be.


Fix:


result = [i * 2 for i in range(10)]


#clcoding.com

Explanation: List comprehensions are more Pythonic, concise, and often faster.



3. Misunderstanding Python’s Scope Rules (LEGB Rule)

Mistake:


x = 10


def example():

    print(x)

    x = 5

example()

Problem: This raises an UnboundLocalError because Python considers x inside example() as a local variable due to the assignment.


Fix:


x = 10


def example():

    global x

    print(x)

    x = 5

example()

#clcoding.com



4. Using print() for Debugging Instead of Proper Debugging Tools

Mistake:


def calculate(x):

    print(f"Debug: x = {x}")

    return x * 2


result = calculate(5)

Problem: Relying on print() statements for debugging can clutter code and is less efficient.


Fix:


def calculate(x):

    return x * 2


result = calculate(5)


# Use a debugger for inspection

import pdb; pdb.set_trace()


#clcoding.com

 

Guidelines for Writing Clean and Maintainable Python Functions

 

1. Simplicity and Clarity

Keep It Simple: Avoid unnecessary complexity. Each function should do one thing and do it well.


Descriptive Naming: Use clear, descriptive names for functions and variables. Avoid abbreviations unless they are widely understood.


Type Annotations: Use type hints to clarify what types of arguments a function expects and what it returns.


def calculate_area(radius: float) -> float:

    return 3.14 * radius * radius


#clcoding.com


2. Avoid Hardcoding

Use Constants: Define constants for values that shouldn't change. Avoid magic numbers.


Parameterization: Make functions flexible by passing parameters instead of hardcoding values. python


PI = 3.14159


def calculate_circumference(radius: float, pi: 

                            float = PI) -> float:

    return 2 * pi * radius


#clcoding.com


3. Readability

Docstrings: Include a docstring that explains what the function does, its parameters, and its return value.


Consistent Indentation: Stick to 4 spaces per indentation level.


Avoid Long Lines: Break lines at 79 characters where possible.


def calculate_bmi(weight: float, height: float) -> float:

    """

    Calculate the Body Mass Index (BMI).


    :param weight: Weight in kilograms.

    :param height: Height in meters.

    :return: BMI value.

    """

    return weight / (height ** 2)


#clcoding.com


4. Testing and Error Handling

Input Validation: Check for invalid inputs and handle them gracefully.


Unit Tests: Write tests for each function. Ensure edge cases are covered.


def divide_numbers(numerator: float, denominator: float) -> float:

    if denominator == 0:

        raise ValueError("Denominator cannot be zero.")

    return numerator / denominator


#clcoding.com


5. Performance

Efficiency: Avoid unnecessary computations. Optimize for performance if the function will be called frequently or handle large data sets.


Avoid Global State: Don’t rely on or modify global variables


def is_prime(n: int) -> bool:

    if n <= 1:

        return False

    if n <= 3:

        return True

    if n % 2 == 0 or n % 3 == 0:

        return False

    i = 5

    while i * i <= n:

        if n % i == 0 or n % (i + 2) == 0:

            return False

        i += 6

    return True


#clcoding.com


6. DRY Principle

Don’t Repeat Yourself: Reuse code by abstracting common functionality into separate functions or modules.


def get_positive_input(prompt: str) -> float:

    value = float(input(prompt))

    if value <= 0:

        raise ValueError("Input must be a +ve number.")

    return value


#clcoding.com

Saturday 3 August 2024

Happy Friendship Day using Python

 



from rich.console import Console

from rich.text import Text

console = Console()

# Create the message and color mapping

text = "Happy Friendship Day!"

colors = [

    "red", "yellow", "green", "cyan", "blue", "white", "magenta",

    "red", "yellow", "green", "cyan", "blue", "magenta", "red",

    "yellow", "green", "white", "cyan", "blue", "magenta", "red"

]

# Generate the colorful message

message = Text()

[message.append(char, style=color) for char,color in zip(text, colors)]

console.print(message)

#clcoding.com

Happy Friendship Day!



Happy Friendship Day using Python

import pyfiglet

from termcolor import colored

text = "Happy Friendship Day!"

fonts = ["slant"]

for i, word in enumerate(text.split()):

    font = pyfiglet.Figlet(font=fonts[i % len(fonts)])

    color = ["red", "green", "yellow", "blue", "magenta"][i % 5]

    ascii_art = font.renderText(word)

    print(colored(ascii_art, color))


#clcoding.com

    __  __                       

   / / / /___ _____  ____  __  __

  / /_/ / __ `/ __ \/ __ \/ / / /

 / __  / /_/ / /_/ / /_/ / /_/ / 

/_/ /_/\__,_/ .___/ .___/\__, /  

           /_/   /_/    /____/   


    ______     _                __     __    _     

   / ____/____(_)__  ____  ____/ /____/ /_  (_)___ 

  / /_  / ___/ / _ \/ __ \/ __  / ___/ __ \/ / __ \

 / __/ / /  / /  __/ / / / /_/ (__  ) / / / / /_/ /

/_/   /_/  /_/\___/_/ /_/\__,_/____/_/ /_/_/ .___/ 

                                          /_/      


    ____              __

   / __ \____ ___  __/ /

  / / / / __ `/ / / / / 

 / /_/ / /_/ / /_/ /_/  

/_____/\__,_/\__, (_)   

            /____/      


Happy Friendship Day using Python

print('\n'.join

 ([''.join

   ([('Friendship'[(x-y)%8 ]

     if((x*0.05)**2+(y*0.1)**2-1)

      **3-(x*0.05)**2*(y*0.1)

       **3<=0 else' ')

        for x in range(-30,30)])

         for y in range(15,-15,-1)]))

print("Happy Friendship Day !!")

#clcoding.com

                                                            

                                                            

                                                            

                shFriends           iendshFri               

            endshFriendshFrie   hFriendshFriendsh           

          iendshFriendshFriendshFriendshFriendshFri         

         iendshFriendshFriendshFriendshFriendshFrien        

        iendshFriendshFriendshFriendshFriendshFriends       

        endshFriendshFriendshFriendshFriendshFriendsh       

        ndshFriendshFriendshFriendshFriendshFriendshF       

        dshFriendshFriendshFriendshFriendshFriendshFr       

        shFriendshFriendshFriendshFriendshFriendshFri       

        hFriendshFriendshFriendshFriendshFriendshFrie       

         riendshFriendshFriendshFriendshFriendshFrie        

          endshFriendshFriendshFriendshFriendshFrie         

          ndshFriendshFriendshFriendshFriendshFrien         

            hFriendshFriendshFriendshFriendshFrie           

             riendshFriendshFriendshFriendshFrie            

              endshFriendshFriendshFriendshFrie             

                shFriendshFriendshFriendshFri               

                  riendshFriendshFriendshFr                 

                    ndshFriendshFriendshF                   

                       FriendshFriends                      

                          ndshFrien                         

                             Fri                            

                              i                             

                                                            

                                                            

                                                            

                                                            

Happy Friendship Day !!


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

 

cl1 = "hello"

cl1_unicode = "hell\u00f6"

print(cl1 != cl1_unicode)

In Python, the comparison cl1 != cl1_unicode checks whether the two strings cl1 and cl1_unicode are different.


Here's the breakdown:

cl1 = "hello": This string contains the characters "h", "e", "l", "l", "o".

cl1_unicode = "hell\u00f6": This string contains the characters "h", "e", "l", "l", followed by the Unicode character \u00f6, which represents "ö".

When comparing cl1 and cl1_unicode:

"hello" is different from "hellö" because the last character in cl1_unicode ("ö") is different from the last character in cl1 ("o").

So, cl1 != cl1_unicode evaluates to True because the strings are not identical.

The print statement outputs True, indicating the strings are not equal.


7 Things I Should’ve Learnt Much Earlier For Python Functions

 

Closures

What: Functions that capture the local state of the environment in which they were created.


Why: Useful for creating function factories or decorators.


def outer(x):

    def inner(y):

        return x + y

    return inner


add_five = outer(5)

print(add_five(10))  

#clcoding.com

Function Annotations

What: Provides a way to attach metadata to function arguments and return values.


Why: Helps in providing hints about the expected data types, which improves code readability.


def add(a: int, b: int) -> int:

    return a + b


print(add(2, 3))  


#clcoding.com

Returning Multiple Values

What: Python allows functions to return multiple values as a tuple.


Why: Enables you to return complex data without creating a class or data structure.


def get_name_age():

    name = "clcoding"

    age = 30

    return name, age


name, age = get_name_age()

print(name, age)  

#clcoding.com

clcoding 30

Docstrings

What: Strings that describe what a function does, placed as the first line within the function body.


Why: Helps in documenting your code, making it more understandable.


def add(a, b):

    """Returns the sum of two numbers."""

    return a + b


print(add.__doc__)  


#clcoding.com

Returns the sum of two numbers.

Lambda Functions

What: Small, anonymous functions defined using lambda.


Why: Useful for short functions that are used once or passed as arguments to higher-order functions.


double = lambda x: x * 2

print(double(5))  


items = [1, 2, 3, 4, 5]

squared = list(map(lambda x: x**2, items))

print(squared)  


#clcoding.com

10

[1, 4, 9, 16, 25]

***args and kwargs

What: args and *kwargs allow functions to accept an arbitrary number of positional and keyword arguments, respectively.


Why: Useful when you don’t know in advance how many arguments will be passed.


def print_args(*args):

    for arg in args:

        print(arg)


print_args(1, 2, 3)  


def print_kwargs(**kwargs):

    for key, value in kwargs.items():

        print(f"{key}: {value}")


print_kwargs(name="clcoding", age=30)

#clcoding.com

1

2

3

name: clcoding

age: 30

Default Arguments

What: Allows you to set default values for function parameters.


Why: Makes your functions more flexible and easier to use.


def greet(name="Guest"):

    print(f"Hello, {name}!")


greet()             

greet("clcoding")   


#clcoding.com

Hello, Guest!

Hello, clcoding!

Wednesday 31 July 2024

Password authentication process using Python

 

Password authentication process using Python

import hashlib, os


def hash_psd(psd: str) -> str:

    salt = os.urandom(16)

    hashed_psd = hashlib.pbkdf2_hmac('sha256',

                                     psd.encode(), salt, 100000)   

    return salt.hex() + hashed_psd.hex()


def verify_psd(stored_psd: str, provided_psd: str) -> bool:    

    salt = bytes.fromhex(stored_psd[:32])

    stored_hash = stored_psd[32:]

    hashed_psd = hashlib.pbkdf2_hmac('sha256',

                                     provided_psd.encode(),salt,100000)

    return hashed_psd.hex() == stored_hash


if __name__ == "__main__":

    psd_to_store = input("Enter a Password: ")

    stored_psd = hash_psd(psd_to_store)

    print(f'Stored Password: {stored_psd}')


    psd_attempt = 'clcoding'

    is_valid = verify_psd(stored_psd, psd_attempt)

    print(f'Password is valid: {is_valid}')


#clcoding.com

Stored Password: ec87cb3f526a3dc27e5a67fe7878f850a6b24c71c2941edc5bbe2c3500afc164cebb1ec8bbbc6a2260faa4825307600e

Password is valid: True

 

 

Saturday 27 July 2024

Olympic data-based analysis using Python



 import pandas as pd

import matplotlib.pyplot as plt

import seaborn as sns

df = pd.read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2021/2021-07-27/olympics.csv')

print(df.head())

medal_counts = df.groupby('team')['medal'].count().reset_index()

medal_counts = medal_counts.sort_values(by='medal', ascending=False).head(10)

print(medal_counts)

top_countries = medal_counts['team'].head(5)

df_top_countries = df[df['team'].isin(top_countries)]

medals_by_year = df_top_countries.groupby(['year', 'team'])['medal'].count().reset_index()

# Plot: Medals Over Time for Top 5 Countries

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

sns.lineplot(data=medals_by_year, x='year', y='medal', hue='team')

plt.title('Medals Over Time for Top 5 Countries')

plt.xlabel('Year')

plt.ylabel('Number of Medals')

plt.legend(title='Country')

plt.show()

# What is the distribution of medals by sport?

medals_by_sport = df.groupby('sport')['medal'].count().reset_index()

medals_by_sport = medals_by_sport.sort_values(by='medal', ascending=False).head(10)

# Plot: Top 10 Sports by Number of Medals

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

sns.barplot(data=medals_by_sport, x='medal', y='sport', palette='viridis')

plt.title('Top 10 Sports by Number of Medals')

plt.xlabel('Number of Medals')

plt.ylabel('Sport')

plt.show()


#clcoding.com 

Thursday 25 July 2024

Olympics Logo using Python

 

import turtle


def draw_ring(color, x, y):

    turtle.penup()

    turtle.color(color)

    turtle.goto(x, y)

    turtle.pendown()

    turtle.circle(50)


turtle.speed(5)

turtle.width(5)

draw_ring("blue", -120, 0)

draw_ring("black", 0, 0)

draw_ring("red", 120, 0)

draw_ring("yellow", -60, -50)

draw_ring("green", 60, -50)

turtle.hideturtle()

turtle.done()

#clcoding.com

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