Saturday, 31 August 2024

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

 


Code:

a = [1, 2, 3]

b = a[:]

a.append(4)

print(b)

Solution and Explanation: 

Step 1: a = [1, 2, 3]

This creates a list a containing the elements [1, 2, 3].

Step 2: b = a[:]

The [:] syntax creates a shallow copy of the list a.

This means that b will be a new list with the same elements as a but stored in a different memory location.

After this line, b contains [1, 2, 3].

Step 3: a.append(4)

The append() method adds the element 4 to the end of the list a.

Now, a contains [1, 2, 3, 4].

However, since b is a separate list (created by the shallow copy), it remains unchanged.

Step 4: print(b)

When you print b, it outputs [1, 2, 3], because b was not modified when a was appended with 4.

Summary:

The key point is that b is a separate copy of the list a at the time of copying. Any subsequent modifications to a do not affect b.

The final output of the code is [1, 2, 3].

Friday, 30 August 2024

How much do know Python's is Operator?

 

1. Comparing Small Integers

a = 100

b = 100


print(a is b)

True

Explanation:


In Python, small integers (typically between -5 and 256) are cached and reused for efficiency.

When you assign 100 to both a and b, they reference the same memory location because they fall within this range.

Thus, a is b returns True because a and b point to the same object in memory.

2. Comparing Large Integers

a = 300

b = 300


print(a is b)

False

Explanation:


Integers outside the small integer cache range (typically beyond 256) are not necessarily cached.

When you assign 300 to both a and b, they may reference different memory locations.

As a result, a is b returns False because a and b do not necessarily point to the same object in memory.


3. Comparing Strings

a = "hello"

b = "hello"


print(a is b)

True

Explanation:


Python optimizes string storage by using interning for identical string literals.

Since both a and b are assigned the same string literal "hello", they point to the same object in memory.

Hence, a is b returns True because a and b reference the same object.

4. Comparing Lists python

a = "hello"

b = "hello"


print(a is b)

True

Explanation:


Lists are mutable and are not interned like small integers or strings.

Even if a and b contain the same elements, they are distinct objects in memory.

Therefore, a is b returns False because a and b do not refer to the same memory location.


5. Comparing Tuples

a = (1, 2, 3)

b = (1, 2, 3)


print(a is b)

False

Explanation:


Tuples with identical content are not always interned or cached by Python.

Although a and b have the same elements, they are separate objects in memory.

Hence, a is b returns False because a and b do not necessarily point to the same object in memory.

Thursday, 29 August 2024

Manhattan Distance in Python

 

Manhattan Distance in Python

def manhattan_distance(point1, point2):

    return sum(abs(a - b) for a, b in zip(point1, point2))


point1 = (1, 2)

point2 = (4, 6)

distance = manhattan_distance(point1, point2)

print(f"Manhattan distance: {distance}")

Manhattan distance: 7

Manhattan Distance Using NumPy

import numpy as np


def manhattan_distance_np(point1, point2):

    return np.sum(np.abs(np.array(point1) - np.array(point2)))


# Example usage

point1 = (1, 2)

point2 = (4, 6)

distance = manhattan_distance_np(point1, point2)

print(f"Manhattan distance (NumPy): {distance}")

Manhattan distance (NumPy): 7

Manhattan Distance Using a Custom Loop

def manhattan_distance_loop(point1, point2):

    distance = 0

    for a, b in zip(point1, point2):

        distance += abs(a - b)

    return distance


# Example usage

point1 = (1, 2)

point2 = (4, 6)

distance = manhattan_distance_loop(point1, point2)

print(f"Manhattan distance (Loop): {distance}")

Manhattan distance (Loop): 7

Manhattan Distance Using Map and Lambda

def manhattan_distance_map(point1, point2):

    return sum(map(lambda a, b: abs(a - b), point1, point2))


# Example usage

point1 = (1, 2)

point2 = (4, 6)

distance = manhattan_distance_map(point1, point2)

print(f"Manhattan distance (Map and Lambda): {distance}")

Manhattan distance (Map and Lambda): 7

Manhattan Distance Using a One-Liner Function

manhattan_distance_oneliner = lambda p1, p2: sum(abs(a - b) for a, b in zip(p1, p2))


# Example usage

point1 = (1, 2)

point2 = (4, 6)

distance = manhattan_distance_oneliner(point1, point2)

print(f"Manhattan distance (One-Liner): {distance}")

Manhattan distance (One-Liner): 7

Manhattan Distance Using List Comprehension

def manhattan_distance_listcomp(point1, point2):

    return sum([abs(a - b) for a, b in zip(point1, point2)])


# Example usage

point1 = (1, 2)

point2 = (4, 6)

distance = manhattan_distance_listcomp(point1, point2)

print(f"Manhattan distance (List Comprehension): {distance}")

Manhattan distance (List Comprehension): 7

Wednesday, 28 August 2024

Django for Everybody Specialization

 


Join Free: Django for Everybody Specialization

Mastering Web Development with Django: A Journey Through the Django Specialization on Coursera

Introduction

Django is one of the most popular web frameworks for Python, known for its "batteries-included" philosophy, which provides developers with a wide range of tools and features right out of the box. Recently, I embarked on a learning journey with the Django Specialization on Coursera, a comprehensive course designed to help learners develop robust and scalable web applications using Django. In this blog, I'll share my experience, the key takeaways from the course, and why Django is an excellent choice for web developers.

What is Django?

Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. It comes with built-in tools for handling common web development tasks such as user authentication, content management, form handling, and more. Django's core principles are simplicity, reusability, and scalability, making it a popular choice for both beginners and seasoned developers.

Overview of the Django Specialization on Coursera

The Django Specialization on Coursera is a multi-course program designed to take you from a beginner to an advanced level in Django. Here’s a breakdown of the courses included in this specialization:

  1. Introduction to Web Development with Django
    This course covers the basics of web development and Django, including setting up your development environment, understanding Django’s Model-View-Template (MVT) architecture, and building your first simple Django app.

  2. Django Features and Libraries
    Focuses on advanced Django features, such as creating reusable apps, working with Django’s built-in libraries, and integrating third-party packages. You’ll learn how to enhance your apps with advanced functionalities and tools.

  3. Django Testing and Deployment
    Covers essential testing strategies and techniques for ensuring the robustness of your web applications. It also dives into deployment strategies, preparing you to launch your Django app on various hosting platforms.

  4. Django Advanced Concepts
    The final course delves into advanced topics such as caching, optimizing database queries, handling complex data relationships, and managing large-scale applications. You’ll gain insights into best practices for maintaining and scaling your Django applications.

My Experience with the Django Specialization

The Django Specialization offered an in-depth exploration of Django, from the basics to more complex concepts. Here are some highlights of my journey:

  1. Learning the Fundamentals
    The first course laid a solid foundation by introducing Django’s architecture and how to set up a project. I learned how to define models, set up URLs, create views, and build templates, which provided a clear understanding of how different components in Django interact.

  2. Exploring Django’s Built-In Tools
    Django comes with a plethora of built-in tools and libraries that simplify common web development tasks. The second course focused on these tools, such as the Django admin interface, which offers a ready-made admin panel for managing data, and the built-in authentication system for user management. This course helped me appreciate Django's "batteries-included" philosophy.

  3. Mastering Testing and Deployment
    I found the third course particularly insightful, as it covered testing strategies to ensure code quality and reliability. Django's built-in testing framework makes it easier to write and run tests, ensuring that your application behaves as expected. The course also covered deployment options, teaching me how to deploy Django apps using various platforms like Heroku and AWS.

  4. Advanced Django Techniques
    The final course pushed me to tackle more advanced Django concepts, such as optimizing query performance and implementing caching mechanisms to speed up the application. It also covered complex database relationships and advanced form handling techniques. This course truly prepared me for building large-scale, production-ready Django applications.

Key Takeaways

  1. Comprehensive Learning Path
    The specialization offers a well-structured learning path, starting from the basics and progressing to advanced topics. This makes it suitable for both beginners and those looking to deepen their Django knowledge.

  2. Practical, Hands-On Experience
    Every course includes hands-on projects that allow you to apply what you've learned immediately. By the end of the specialization, I had built several Django applications, each more complex than the last, which greatly improved my confidence and skills.

  3. Real-World Applications
    The specialization focused on building real-world applications, such as blogs, e-commerce sites, and content management systems. This practical approach helps you understand how Django can be applied in various scenarios.

  4. Deployment and Scalability
    One of the most valuable aspects of the course was learning about deployment and scalability. Knowing how to deploy an app securely and scale it as traffic grows is critical for any web developer.

Why Choose Django?

  1. Rapid Development: Django allows for rapid development by providing a robust framework that takes care of many of the common web development tasks, such as handling user authentication and creating a secure admin interface.

  2. Security: Django has several built-in security features, including protection against common web vulnerabilities like SQL injection, cross-site scripting (XSS), and cross-site request forgery (CSRF).

  3. Scalability and Versatility: Django is suitable for both small-scale and large-scale applications, offering scalability as your application grows. It's used by some of the world's largest websites, such as Instagram and Pinterest.

  4. Strong Community and Extensive Documentation: Django has a vibrant community and extensive documentation, making it easier to find help and resources.

Conclusion

The Django Specialization on Coursera is an excellent investment for anyone looking to learn or deepen their knowledge of Django. Whether you're a beginner just starting with web development or an experienced developer looking to explore Django's advanced features, this course has something for everyone. The hands-on projects, practical applications, and comprehensive curriculum make it a fantastic way to master Django.

If you’re looking to build powerful, scalable web applications with Python, Django is a framework worth learning, and this Coursera specialization is a great place to start.

Introduction to Flask framework

 


A Quick Dive into Flask Framework for Beginners!

🚀 Just finished the "Introduction to Flask Framework" project on Coursera, and here’s a quick rundown of what I learned! 🧵👇

1️⃣ What is Flask?
Flask is a micro web framework for Python. It’s lightweight, flexible, and perfect for beginners to start building web applications. No unnecessary complexity, just the essentials! 🔍

2️⃣ Getting Started with Flask
The course starts with the basics: setting up your environment, installing Flask, and creating a simple “Hello, World!” app. 🖥️ Easy to follow and great for understanding the core concepts.

3️⃣ Building Dynamic Web Pages
Learned to create dynamic web pages using HTML templates and Flask’s Jinja2 template engine! 🎨 Now, I can pass variables to my templates and make interactive web pages. 💻✨

4️⃣ Handling User Inputs
Got hands-on with form creation and data handling! Flask makes it super easy to handle user input securely. 📝🔒

5️⃣ Deploying a Flask App
Finally, deployed my app to the web! 🌐 Learned about deployment options and how to get my app online with tools like Heroku. 💾🚀

6️⃣ Key Takeaways

  • Flask is perfect for beginners due to its simplicity.
  • Building a basic app from scratch gives you a strong foundation.
  • Deploying is easier than I thought, and it’s so rewarding to see your app live! 🙌

7️⃣ My Advice for Flask Newbies

  • Start small and build up! 🛠️
  • Don’t skip reading the Flask docs – they’re incredibly helpful! 📚
  • Practice deploying, even if it’s just a simple app. It’s great experience! 🌍

🔗 If you're interested in learning Flask, check out the course here. It’s perfect for beginners and super hands-on!

Happy coding! 😊💻 #Flask #Python #WebDevelopment #LearnToCode #CodingJourney #FlaskFramework

Join Free: Introduction to Flask framework

Flask for Beginners: Creating an Application

 


Getting Started with Flask: Creating Your First Web Application

Introduction

Flask is a lightweight and versatile Python web framework that's perfect for beginners looking to develop their first web application. It's easy to set up, requires minimal coding, and offers the flexibility to build everything from simple web pages to complex, data-driven applications. Recently, I took a Coursera project titled "Flask for Beginners: Creating an Application," which provided a hands-on introduction to Flask and helped me build a basic web application step-by-step. Here, I’ll share my learning experience and provide an overview of what to expect from the course.

What is Flask?

Flask is a micro web framework for Python, designed to be lightweight, easy to use, and flexible. It allows developers to quickly set up a web server, handle HTTP requests, and render dynamic content. Unlike larger frameworks like Django, Flask does not come with many built-in tools or components, giving developers more freedom to choose the best tools and libraries for their specific needs.

Why Choose Flask?

Flask is an excellent choice for beginners for several reasons:

  1. Simplicity and Minimalism: Flask's core philosophy is "less is more," providing a simple foundation with which you can build your application.
  2. Flexibility: It doesn't force you into a specific project structure, allowing you to choose the tools and technologies that best suit your needs.
  3. Extensive Documentation: Flask has comprehensive documentation and a large community, making it easier for beginners to find resources and support.

My Experience with the Coursera Project

The Coursera project "Flask for Beginners: Creating an Application" is designed as a hands-on, interactive learning experience. It provides a step-by-step guide to building a simple web application using Flask. Here's a quick overview of the key stages of the project:

  1. Setting Up the Environment: The course starts by helping you set up your development environment with Python and Flask. You'll learn how to install Flask using pip and create a virtual environment to manage dependencies.

  2. Creating a Basic Flask Application: You'll write your first Flask application by creating a simple "Hello, World!" web page. This involves understanding Flask's routing mechanism, which maps URLs to functions in your code.

  3. Building Dynamic Content: The course then moves on to creating dynamic content with HTML templates and Jinja2, Flask's templating engine. You'll learn how to pass variables from your Python code to your HTML templates, making your web pages more interactive.

  4. Handling User Input: One of the most critical parts of any web application is handling user input. The course covers how to create forms and handle data submissions securely, using Flask's built-in form-handling capabilities.

  5. Deploying Your Application: Finally, you'll learn how to deploy your Flask application to the web so that it's accessible to anyone online. The course discusses various hosting options and provides a basic overview of deployment tools like Heroku.

Key Takeaways

  1. Understanding the Basics of Flask: The project gave me a solid foundation in Flask, from setting up a development environment to creating dynamic web pages.
  2. Building a Simple Web Application: By the end of the course, I had built a simple yet functional web application, reinforcing my understanding of web development fundamentals.
  3. Practical Experience with Deployment: Learning how to deploy a web application was an invaluable experience, giving me insights into real-world considerations when launching an app.
  4. Boosting Confidence: As someone new to Flask, this project boosted my confidence in working with Python web frameworks and opened the door to more advanced web development projects.

Tips for Beginners

  • Start Small: Begin with a simple project to get familiar with Flask's core concepts.
  • Read the Documentation: Flask's official documentation is an excellent resource. Take the time to read through it and understand the framework's capabilities.
  • Experiment and Explore: Don’t be afraid to experiment with different features and libraries. Flask is highly extensible, and there are many tools you can integrate to enhance your application.
  • Practice Deployment: Getting your application online can be one of the most rewarding parts of web development. Try deploying your project to a free platform like Heroku to gain practical experience.

Conclusion

The "Flask for Beginners: Creating an Application" project on Coursera is an excellent starting point for anyone interested in learning Flask and web development with Python. It offers a hands-on approach, allowing you to build a real web application while learning the essentials of web frameworks. If you are looking to expand your web development skills or just curious about Flask, I highly recommend giving this course a try.

Whether you're building a simple website or a complex web application, Flask is a powerful tool in the Python ecosystem that is worth exploring. Happy coding!


By taking this course, I gained a solid foundation in Flask and the confidence to dive deeper into web development. 

Join Free: Flask for Beginners: Creating an Application

Create Your First Web App with Python and Flask

 


What you'll learn

Create Web Applications with Flask

Use WTForms and SQLAlchemy in Flask Applications

Use Templates in Flask Applications

Join Free: Create Your First Web App with Python and Flask

About this Guided Project

In this 2-hour long project-based course, you will learn the basics of web application development with Python using the Flask framework. Through hands on, practical experience, you will go through concepts like creating a Flask Application, using Templates in Flask Applications, using SQLAlchemy and SQLite with Flask, and using Flask and WTForms. You will then apply the concepts to create your first web application with Python and Flask.

This course is aimed at learners who are looking to get started with web application development using Python, and have some prior programming experience in the Python programming language. The ideal learner has understanding of Python syntax, HTML syntax, and computer programming concepts.

Note: This course works best for learners who are based in the North America region. We’re currently working on providing the same experience in other regions.

Developing AI Applications with Python and Flask

 


What you'll learn

Describe the steps and processes involved in creating a Python application including the application development lifecycle 

Create Python modules, run unit tests, and package applications while ensuring the PEP8 coding best practices

Explain the features of Flask and deploy applications on the web using the Flask framework

Create and deploy an AI-based application onto a web server using IBM Watson AI Libraries and Flask

Join Free: Developing AI Applications with Python and Flask

There are 3 modules in this course

This mini course is intended to apply basic Python skills for developing Artificial Intelligence (AI) enabled applications. In this hands-on project you will assume the role of a developer and perform tasks including:  

- Develop functions and application logic 
- Exchange data using Watson AI libraries
- Write unit tests, and 
- Package the application for distribution. 

You will demonstrate your foundational Python skills by employing different techniques to develop web applications and AI powered solutions. After completing this course, you will have added another project to your portfolio and gained the confidence to begin developing AI enabled applications using Python and Flask, Watson AI libraries, build and run unit tests, and package the application for distribution out in the real world.

Tuesday, 27 August 2024

5 Practical Python Programs Using the Pickle Library

 

1. Saving and Loading a List

This program saves a list to a file and then loads it back.


import pickle


my_list = ['apple', 'banana', 'cherry']


with open('list.pkl', 'wb') as file:

    pickle.dump(my_list, file)


with open('list.pkl', 'rb') as file:

    loaded_list = pickle.load(file)


print("Loaded List:", loaded_list)


#source code --> clcoding.com

Loaded List: ['apple', 'banana', 'cherry']



2. Saving and Loading a Dictionary

This program demonstrates saving a dictionary to a file and loading it back.


import pickle


my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}


with open('dict.pkl', 'wb') as file:

    pickle.dump(my_dict, file)


with open('dict.pkl', 'rb') as file:

    loaded_dict = pickle.load(file)


print("Loaded Dictionary:", loaded_dict)


#source code --> clcoding.com

Loaded Dictionary: {'name': 'John', 'age': 30, 'city': 'New York'}



3. Saving and Loading a Custom Object

This program saves an instance of a custom class to a file and loads it back.


import pickle


class Person:

    def __init__(self, name, age):

        self.name = name

        self.age = age


    def __repr__(self):

        return f"Person(name={self.name}, age={self.age})"


person = Person('Alice', 25)


with open('person.pkl', 'wb') as file:

    pickle.dump(person, file)


with open('person.pkl', 'rb') as file:

    loaded_person = pickle.load(file)


print("Loaded Person:", loaded_person)


#source code --> clcoding.com

Loaded Person: Person(name=Alice, age=25)



4. Saving and Loading a Tuple

This program saves a tuple to a file and loads it back.


import pickle


my_tuple = (10, 20, 30, 'Hello')


with open('tuple.pkl', 'wb') as file:

    pickle.dump(my_tuple, file)


with open('tuple.pkl', 'rb') as file:

    loaded_tuple = pickle.load(file)


print("Loaded Tuple:", loaded_tuple)


#source code --> clcoding.com

Loaded Tuple: (10, 20, 30, 'Hello')



5. Saving and Loading Multiple Objects

This program saves multiple objects to a single file and loads them back.


import pickle


list_data = [1, 2, 3]

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

string_data = "Hello, World!"


with open('multiple.pkl', 'wb') as file:

    pickle.dump(list_data, file)

    pickle.dump(dict_data, file)

    pickle.dump(string_data, file)


with open('multiple.pkl', 'rb') as file:

    loaded_list = pickle.load(file)

    loaded_dict = pickle.load(file)

    loaded_string = pickle.load(file)


print("Loaded List:", loaded_list)

print("Loaded Dictionary:", loaded_dict)

print("Loaded String:", loaded_string)


#source code --> clcoding.com

Loaded List: [1, 2, 3]

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

Loaded String: Hello, World!


7 Lesser-Known Python Techniques about Lists

 

1. Flatten a Nested List

Flatten a deeply nested list into a single list of elements.


from collections.abc import Iterable


def flatten(lst):

    for item in lst:

        if isinstance(item, Iterable) and not isinstance(item, str):

            yield from flatten(item)

        else:

            yield item


nested_list = [1, [2, 3, [4, 5]], 6]

flat_list = list(flatten(nested_list))

print(flat_list)  

[1, 2, 3, 4, 5, 6]


2. List of Indices for Specific Value

Get all indices of a specific value in a list.


lst = [10, 20, 10, 30, 10, 40]

indices = [i for i, x in enumerate(lst) if x == 10]

print(indices) 

[0, 2, 4]

3. Transpose a List of Lists (Matrix)

Transpose a matrix-like list (switch rows and columns).


matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

transposed = list(map(list, zip(*matrix)))

print(transposed)  

[[1, 4, 7], [2, 5, 8], [3, 6, 9]]



4. Rotate a List

Rotate the elements of a list by n positions.


def rotate(lst, n):

    return lst[-n:] + lst[:-n]


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

rotated_lst = rotate(lst, 2)

print(rotated_lst) 

[4, 5, 1, 2, 3]

5. Find Duplicates in a List

Identify duplicate elements in a list.


from collections import Counter


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

duplicates = [item for item, count in Counter(lst).items() if count > 1]

print(duplicates)  

[2, 4]


6. Chunk a List

Split a list into evenly sized chunks.


def chunk(lst, n):

    for i in range(0, len(lst), n):

        yield lst[i:i + n]


lst = [1, 2, 3, 4, 5, 6, 7, 8]

chunks = list(chunk(lst, 3))

print(chunks)  

[[1, 2, 3], [4, 5, 6], [7, 8]]

7. Remove Consecutive Duplicates

Remove consecutive duplicates from a list, preserving order.


from itertools import groupby


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

result = [key for key, _ in groupby(lst)]

print(result)  

[1, 2, 3, 4, 5]

Monday, 26 August 2024

Barcode using Python

 

pip install python-barcode


import barcode

from barcode.writer import ImageWriter

from IPython.display import Image, display


barcode_format = barcode.get_barcode_class('ean13')


barcode_number = '123456789012'


barcode_image = barcode_format(barcode_number, writer=ImageWriter())


barcode_filename = 'barcode_image'

barcode_image.save(barcode_filename)


display(Image(filename=f'{barcode_filename}.png'))

Sunday, 25 August 2024

Color code using Python

 

from webcolors import name_to_hex


def color_name_to_code(color_name):

    try:

        color_code = name_to_hex(color_name)

        return color_code

    except ValueError:

        return None

colorname = input("Enter color name : ")

result_code = color_name_to_code(colorname)

print(result_code)  


from webcolors import hex_to_name


def color_code_to_name(color_code):

    try:

        color_name = hex_to_name(color_code)

        return color_name

    except ValueError:

        return None

colorcode = input("Enter color code : ")

result_name = color_code_to_name(colorcode)

print(result_name)  

Saturday, 24 August 2024

Phone Number Handling in Python

 

1. Parse and Format a Phone Number

This program parses a phone number and formats it in the international format.


import phonenumbers

from phonenumbers import PhoneNumberFormat, format_number


phone_number = phonenumbers.parse("+14155552671", "US")


formatted_number = format_number(phone_number, PhoneNumberFormat.INTERNATIONAL)


print(f"Formatted Number: {formatted_number}")

Formatted Number: +1 415-555-2671

2. Validate a Phone Number

This program checks whether a phone number is valid or not.


import phonenumbers


phone_number = phonenumbers.parse("+14155552671", "US")


is_valid = phonenumbers.is_valid_number(phone_number)


print(f"Is the phone number valid? {'Yes' if is_valid else 'No'}")

Is the phone number valid? Yes


3. Get the Location of a Phone Number

This program retrieves the location associated with a phone number.


import phonenumbers

from phonenumbers import geocoder


phone_number = phonenumbers.parse("+14155552671", "US")


location = geocoder.description_for_number(phone_number, "en")


print(f"Location: {location}")


#source Code --> clcoding.com

Location: San Francisco, CA

4. Carrier Detection

This program detects the carrier of a given phone number.


import phonenumbers

from phonenumbers import carrier


phone_number = phonenumbers.parse("+14155552671", "US")


phone_carrier = carrier.name_for_number(phone_number, "en")


print(f"Carrier: {phone_carrier}")


#source Code --> clcoding.com

Carrier: 


5. Time Zone Detection

This program retrieves the time zones associated with a phone number.


import phonenumbers

from phonenumbers import timezone


phone_number = phonenumbers.parse("+14155552671", "US")


time_zones = timezone.time_zones_for_number(phone_number)


print(f"Time Zones: {', '.join(time_zones)}")


#source Code --> clcoding.com

Time Zones: America/Los_Angeles

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


Code:

a = [1, 2, 3]

b = a

a.append(4)

print(b)

Solution and Explanantion: 

 a = [1, 2, 3]:

This line creates a list a with elements [1, 2, 3].

b = a:

Here, b is not a new list but a reference to the same list object that a refers to. In Python, variables that hold lists (and other mutable objects) actually hold references to the memory location where the list is stored. So, b now refers to the same list as a.

a.append(4):

This line adds the element 4 to the end of the list a. Since a and b refer to the same list, this modification affects both a and b.

print(b):

Since b refers to the same list as a, the output will show the modified list [1, 2, 3, 4].

Final Output:

[1, 2, 3, 4]

The key concept here is that a and b are references to the same list in memory, so changes to the list via one variable are reflected in the other.

Fetching and Displaying Periodic Table Data in Python


 Periodic Table Data in Python

pip install chempy


from chempy.util import periodic


n = int(input("Enter number to see the table: "))

print("Atomic No.\tName\t\tSymbol\t\tMass")


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

    print(i, end="\t\t")

    if len(periodic.names[i]) > 7:

        print(periodic.names[i], end="\t")

    else:

        print(periodic.names[i], end="\t\t")

    print(periodic.symbols[i], end="\t\t")

    print(periodic.relative_atomic_masses[i])

#source code --> clcoding.com

Atomic No. Name Symbol Mass

1 Helium He 4.002602

2 Lithium Li 6.94

3 Beryllium Be 9.0121831

4 Boron B 10.81

5 Carbon C 12.011

6 Nitrogen N 14.007

7 Oxygen O 15.999

8 Fluorine F 18.998403163

9 Neon Ne 20.1797

10 Sodium Na 22.98976928

11 Magnesium Mg 24.305

12 Aluminium Al 26.9815384

13 Silicon Si 28.085

14 Phosphorus P 30.973761998

15 Sulfur S 32.06

16 Chlorine Cl 35.45

17 Argon Ar 39.95

18 Potassium K 39.0983

19 Calcium Ca 40.078

20 Scandium Sc 44.955908

Friday, 23 August 2024

IP Address Manipulation with Python



1. Check if an IP Address is Private

This program checks whether an IP address belongs to a private range.


import ipaddress


def check_private_ip(ip):

    try:

        ip_obj = ipaddress.ip_address(ip)

        return ip_obj.is_private

    except ValueError:

        return False


ip = "192.168.0.1"

print(f"Is {ip} private? {check_private_ip(ip)}")


#source code --> clcoding.com

Is 192.168.0.1 private? True


2. Calculate the Network Range from a CIDR Notation

This program calculates the network range from a given CIDR notation.


import ipaddress


def get_network_range(cidr):

    try:

        network = ipaddress.ip_network(cidr, strict=False)

        return (network.network_address, network.broadcast_address)

    except ValueError:

        return None


cidr = "192.168.1.0/24"

network_range = get_network_range(cidr)

if network_range:

    print(f"Network range: {network_range[0]} - {network_range[1]}")


#source code --> clcoding.com

Network range: 192.168.1.0 - 192.168.1.255


3. Check if an IP Address is in a Specific Network

This program checks if a given IP address is part of a specified network.


import ipaddress


def ip_in_network(ip, network):

    try:

        network_obj = ipaddress.ip_network(network, strict=False)

        ip_obj = ipaddress.ip_address(ip)

        return ip_obj in network_obj

    except ValueError:

        return False


ip = "192.168.1.10"

network = "192.168.1.0/24"

print(f"Is {ip} in network {network}? {ip_in_network(ip, network)}")


#source code --> clcoding.com

Is 192.168.1.10 in network 192.168.1.0/24? True


4. Generate All IP Addresses in a Network

This program generates all possible IP addresses within a given network.


import ipaddress


def generate_ips_in_network(network):

    try:

        network_obj = ipaddress.ip_network(network, strict=False)

        return [str(ip) for ip in network_obj.hosts()]

    except ValueError:

        return []


network = "192.168.1.0/30"

ips = generate_ips_in_network(network)

print(f"IP addresses in {network}: {ips}")


#source code --> clcoding.com

IP addresses in 192.168.1.0/30: ['192.168.1.1', '192.168.1.2']


5. Convert Integer to IPv4 Address

This program converts an integer back to its corresponding IPv4 address.


import ipaddress


def int_to_ipv4(integer):

    try:

        return str(ipaddress.IPv4Address(integer))

    except ValueError:

        return None


ipv4_int = 3232235777

print(f"Integer: {ipv4_int} -> IPv4: {int_to_ipv4(ipv4_int)}")


#source code --> clcoding.com

Integer: 3232235777 -> IPv4: 192.168.1.1

Wireframes and Surface Plots in Python

 

import numpy as np

import matplotlib.pyplot as plt

from mpl_toolkits.mplot3d import Axes3D


x = np.linspace(-5, 5, 50); y = np.linspace(-5, 5, 50)

X, Y = np.meshgrid(x, y)

Z = np.sin(np.sqrt(X**2 + Y**2))


fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')

ax.plot_wireframe(X, Y, Z, color='blue')


ax.set_xlabel('X axis',); ax.set_ylabel('Y axis')

ax.set_zlabel('Z axis')

plt.show()

#source Code --> clcoding.com


import numpy as np

import matplotlib.pyplot as plt

from mpl_toolkits.mplot3d import Axes3D


x = np.linspace(-5, 5, 50); y = np.linspace(-5, 5, 50)

X, Y = np.meshgrid(x, y)

Z = np.sin(np.sqrt(X**2 + Y**2))


fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')

surface = ax.plot_surface(X, Y, Z, cmap='viridis')

fig.colorbar(surface, ax=ax, shrink=0.5, aspect=5)


ax.set_xlabel('X axis'); ax.set_ylabel('Y axis')

ax.set_zlabel('Z axis')

plt.show()

Wednesday, 21 August 2024

10 Essential Use Cases of Python's zip() Function with Examples

 

1. Combining Two Lists

Use case: Merging two lists element-wise.

names = ["Alice", "Bob", "Charlie"]

ages = [25, 30, 35]


combined = list(zip(names, ages))

print(combined)  

[('Alice', 25), ('Bob', 30), ('Charlie', 35)]

2. Unzipping Lists

Use case: Splitting paired data into separate lists.


combined = [('Alice', 25), ('Bob', 30), ('Charlie', 35)]


names, ages = zip(*combined)

print(names)  

print(ages)   

('Alice', 'Bob', 'Charlie')

(25, 30, 35)



3. Iterating Over Multiple Lists Simultaneously

Use case: Useful when you need to iterate through multiple lists at the same time.


subjects = ['Math', 'Science', 'English']

scores = [88, 92, 85]


for subject, score in zip(subjects, scores):

    print(f"{subject}: {score}")

Math: 88

Science: 92

English: 85

4. Creating Dictionaries

Use case: Creating dictionaries from two lists: one for keys, one for values.


keys = ['name', 'age', 'city']

values = ['Alice', 25, 'New York']


dictionary = dict(zip(keys, values))

print(dictionary)  

{'name': 'Alice', 'age': 25, 'city': 'New York'}


5. Combining Multiple Lists

Use case: Zipping more than two lists together.


list1 = [1, 2, 3]

list2 = ['a', 'b', 'c']

list3 = [True, False, True]


combined = list(zip(list1, list2, list3))

print(combined)  

[(1, 'a', True), (2, 'b', False), (3, 'c', True)]

6. Handling Different Length Iterables

Use case: When lists have different lengths, zip() stops at the shortest one.


list1 = [1, 2, 3]

list2 = ['a', 'b']


combined = list(zip(list1, list2))

print(combined)  

[(1, 'a'), (2, 'b')]



7. Working with Ranges

Use case: Zipping together ranges or sequences.


numbers = range(1, 4)

letters = ['a', 'b', 'c']


result = list(zip(numbers, letters))

print(result)  

[(1, 'a'), (2, 'b'), (3, 'c')]

8. Comparing Elements of Two Lists

Use case: Zipping two lists to compare elements.


list1 = [1, 2, 3]

list2 = [1, 4, 3]


comparison = [a == b for a, b in zip(list1, list2)]

print(comparison)

[True, False, True]



9. Transpose a Matrix

Use case: Use zip() to transpose rows and columns of a 2D matrix.


matrix = [

    [1, 2, 3],

    [4, 5, 6],

    [7, 8, 9]

]


transposed = list(zip(*matrix))

print(transposed) 

[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

10. Zipping with Enumerate

Use case: Zipping with an enumerated list for indexed pairings.


data = ['apple', 'banana', 'cherry']

indexed_data = list(zip(range(1, len(data) + 1), data))

print(indexed_data)  

[(1, 'apple'), (2, 'banana'), (3, 'cherry')]

Tuesday, 20 August 2024

How to Use Python f-Strings?

 

Basic Usage

Here's a basic example of using f-strings:


name = "Alice"

age = 30


greeting = f"Hello, my name is {name} and I am {age} years old."

print(greeting)

Hello, my name is Alice and I am 30 years old.

Embedding Expressions

You can also embed expressions directly inside f-strings:


length = 5

width = 3


area = f"The area of the rectangle is {length * width} square units."

print(area)

The area of the rectangle is 15 square units.



Formatting Numbers

F-strings also allow you to format numbers:


pi = 3.141592653589793


formatted_pi = f"Pi rounded to two decimal places is {pi:.2f}."

print(formatted_pi)

Pi rounded to two decimal places is 3.14.

Using Functions Inside F-Strings

You can even call functions within an f-string:


def greet(name):

    return f"Hello, {name}!"


message = f"{greet('Alice')}"

print(message)

Hello, Alice!



Multi-line F-Strings

F-strings can also be used with multi-line strings:


name = "Alice"

age = 30


info = (

    f"Name: {name}\n"

    f"Age: {age}\n"

    f"Location: Wonderland"

)

print(info)

Name: Alice

Age: 30

Location: Wonderland



Combining F-Strings with Other String Formatting

F-strings can be combined with other string formatting methods if necessary:


name = "Alice"

age = 30


combined = f"Name: {name}, " + "Age: {}".format(age)

print(combined)

Name: Alice, Age: 30

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()


Popular Posts

Categories

AI (32) 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 (21) 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 (888) Python Coding Challenge (285) 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