python_codes | Unsorted

Telegram-канал python_codes - Python Codes

-

This channel will serve you all the codes and programs which related to Python. We post the codes from the beginner level to advance level. Admin : @Only_Mahi

Subscribe to a channel

Python Codes

💡 Python Tip: Do you know Ellipsis(...) can be used as a placeholder in Python, just like a 𝘱𝘢𝘴𝘴 statement?

@Python_Codes

Читать полностью…

Python Codes

Useful Pandas🐼 method you should definitely know

✅ head()
✅ info()
✅ fillna()
✅ melt()
✅ pivot()
✅ query()
✅ merge()
✅ assign()
✅ groupby()
✅ describe()
✅ sample()
✅ replace()
✅ rename()


@Python_Codes

Читать полностью…

Python Codes

Do you know abou .strip()

From the above example you can see that it removed all the characters mentioned in .strip('comw.') and returns the remaining string


@Python_Codes

Читать полностью…

Python Codes

To shuffle pandas DataFrame df (in a reproducible way):

df = df.sample(frac=1, random_state=123).reset_index(drop=True)

Alternatively, you can use sklearn.utils.shuffle().

#pandas

@Python_Codes

Читать полностью…

Python Codes

Guess the Number Game in Python

@Python_Codes

Читать полностью…

Python Codes

What Is FastAPI?

FastAPI is a modern, high-performance web framework for building APIs with Python based on standard type hints.


It has the following key features:

👉Fast to run: It offers very high performance, on par with NodeJS and Go, thanks to Starlette and pydantic.

👉Fast to code: It allows for significant increases in development speed.

👉Reduced number of bugs: It reduces the possibility for human-induced errors.

👉Intuitive: It offers great editor support, with completion everywhere and less time debugging.

👉Straightforward: It’s designed to be uncomplicated to use and learn, so you can spend less time reading documentation.

👉Short: It minimizes code duplication.

👉Robust: It provides production-ready code with automatic interactive documentation.

👉Standards-based: It’s based on the open standards for APIs, OpenAPI and JSON Schema.

You can use this instead of Django and Flask

Share and Support
@Python_Codes

Читать полностью…

Python Codes

Inverts a dictionary with non-unique hashable values.

👉Create a collections.defaultdict with list as the default value for each key.

👉Use dictionary.items() in combination with a loop to map the values of the dictionary to keys using dict.append().

👉Use dict() to convert the collections.defaultdict to a regular dictionary.

CODE:

from collections import defaultdict

def collect_dictionary(obj):
inv_obj = defaultdict(list)
for key, value in obj.items():
inv_obj[value].append(key)
return dict(inv_obj)

Example:

ages = {
'Peter': 10,
'Isabel': 10,
'Anna': 9,
}
collect_dictionary(ages)

Output: { 10: ['Peter', 'Isabel'], 9: ['Anna'] }

Share and Support
@Python_Codes

Читать полностью…

Python Codes

What is the difference between append() and extend() methods?

Both append() and extend() methods are methods used to add elements at the end of a list.

👉append(element): Adds the given element at the end of the list that called this append() method

👉extend(another-list): Adds the elements of another list at the end of the list that called this extend() method

Share and Support
@Python_Codes

Читать полностью…

Python Codes

What is the lambda function in Python?

A lambda function is an anonymous function (a function that does not have a name) in Python. To define anonymous functions, we use the ‘lambda’ keyword instead of the ‘def’ keyword, hence the name ‘lambda function’. Lambda functions can have any number of arguments but only one statement.

Example:

l = lambda x,y : x*y
print(a(5, 6))

Output:30

Share and Support
@Python_Codes

Читать полностью…

Python Codes

What is a map function in Python?

The map() function in Python has two parameters, function and iterable. The map() function takes a function as an argument and then applies that function to all the elements of an iterable, passed to it as another argument. It returns an object list of results.

Example:

def calculateSq(n):
return n*n
numbers = (2, 3, 4, 5)
result = map( calculateSq, numbers)
print(result)

Share and Support
@Python_Codes

Читать полностью…

Python Codes

What are the common built-in data types in Python?

Python supports the below-mentioned built-in data types:

Immutable data types:

👉Number
👉String
👉Tuple

Mutable data types:

👉List
👉Dictionary
👉set

Share and Support
@Python_Codes

Читать полностью…

Python Codes

What is scope resolution?

👉 A scope is a block of code where an object in Python remains relevant.Each and every object of python functions within its respective scope.As Namespaces uniquely identify all the objects inside a program but these namespaces also have a scope defined for them where you could use their objects without any prefix. It defines the accessibility and the lifetime of a variable.

Let’s have a look on scope created as the time of code execution:

👉A local scope refers to the local objects included in the current function.

👉A global scope refers to the objects that are available throughout execution of the code.

👉A module-level scope refers to the global objects that are associated with the current module in the program.

👉An outermost scope refers to all the available built-in names callable in the program.

Share and Support
@Python_Codes

Читать полностью…

Python Codes

What are python namespaces?

👉A Python namespace ensures that object names in a program are unique and can be used without any conflict. Python implements these namespaces as dictionaries with ‘name as key’ mapped to its respective ‘object as value’.

Let’s explore some examples of namespaces:

👉Local Namespace consists of local names inside a function. It is temporarily created for a function call and gets cleared once the function returns.

👉Global Namespace consists of names from various imported modules/packages that are being used in the ongoing project. It is created once the package is imported into the script and survives till the execution of the script.

👉Built-in Namespace consists of built-in functions of core Python and dedicated built-in names for various types of exceptions.

Share and Support
@Python_Codes

Читать полностью…

Python Codes

Time complexity in above Picture

Fibonacci Number using Recursion


CODE
:

def fib(n):
if n <= 0: # base case 1
return 0
if n <= 1: # base case 2
return 1
else: # recursive step
return fib(n-1) + fib(n-2)

Share and Support
@Python_Codes

Читать полностью…

Python Codes

#numpy

NumPy

Smart use of ‘:’ to extract the right shape


Sometimes you encounter a 3-dim array that is of shape (N, T, D), while your function requires a shape of (N, D). At a time like this, reshape() will do more harm than good, so you are left with one simple solution:

Example:

for t in xrange(T):
x[:, t, :] = # ...


Share and Support
@Python_Codes

Читать полностью…

Python Codes

Program to create a Countdown Timer

@Python_Codes

Читать полностью…

Python Codes

The simplest way to flatten a list in python.


@Python_Codes

Читать полностью…

Python Codes

3 Ways to merge Dictionaries in python

@Python_Codes

Читать полностью…

Python Codes

Indian Flag Using Python

@Python_Codes

Читать полностью…

Python Codes

Difference between list and tuple in python

🔸List is mutable ( you can modify the original list) and it's values are written in sqare brackets [ ]

🔸Tuple is immutable ( you can't modify it) and it's values are written in parentheses ( ) delimited by comma( , )

🔸To convert list to tuple - we use tuple() function
list1 = [1,2,3]
print(tuple(list1)) Output : (1,2,3)

🔸 For single element list
list1 = [1]
print(tuple(list1)) Output : (1, )

▪️a tuple is a tuple because of comma not because of parentheses


@Python_Codes

Читать полностью…

Python Codes

Walrus operator:

The Walrus or := operator is one of the latest additions to python 3.8.
It is an assignment operator that lets you assign value to a variable within an expression like conditional statements, loops, etc.


Example

If we want to check and print the length of a list:

Mylist = [1,2,3]
if(l := len(mylist) > 2)
print(l)


Output

3

Share and Support
@Python_Codes

Читать полностью…

Python Codes

How is Multithreading achieved in Python?

👉Python has a multi-threading package ,but commonly not considered as good practice to use it as it will result in increased code execution time.

👉Python has a constructor called the Global Interpreter Lock (GIL). The GIL ensures that only one of your ‘threads’ can execute at one time.The process makes sure that a thread acquires the GIL, does a little work, then passes the GIL onto the next thread.

👉This happens at a very Quick instance of time and that’s why to the human eye it seems like your threads are executing parallely, but in reality they are executing one by one by just taking turns using the same CPU core.

Share and Support
@Python_Codes

Читать полностью…

Python Codes

What is self in Python?

Self is an object or an instance of a class. This is explicitly included as the first parameter in Python. On the other hand, in Java it is optional. It helps differentiate between the methods and attributes of a class with local variables.

The self variable in the init method refers to the newly created object, while in other methods, it refers to the object whose method was called.

Syntax:

Class A:
def func(self):
print(“Hi”)

Share and Support
@Python_Codes

Читать полностью…

Python Codes

Explain all file processing modes supported in Python?

Python has various file processing modes.

For opening files, there are three modes:

👉read-only mode (r)
👉write-only mode (w)
👉read–write mode (rw)

For opening a text file using the above modes, we will have to append ‘t’ with them as follows:

👉read-only mode (rt)
👉write-only mode (wt)
👉read–write mode (rwt)

Similarly, a binary file can be opened by appending ‘b’ with them as follows:

👉read-only mode (rb)
👉write-only mode (wb)
👉read–write mode (rwb)

To append the content in the files, we can use the append mode (a):

For text files, the mode would be ‘at’
For binary files, it would be ‘ab’

Share and Support
@Python_Codes

Читать полностью…

Python Codes

Explain split(), sub(), subn() methods of “re” module in Python?

These methods belong to the Python RegEx or ‘re’ module and are used to modify strings.

👉split(): This method is used to split a given string into a list.

👉sub(): This method is used to find a substring where a regex pattern matches, and then it replaces the matched substring with a different string.

👉subn(): This method is similar to the sub() method, but it returns the new string, along with the number of replacements.

Share and Support
@Python_Codes

Читать полностью…

Python Codes

What is __init__ in Python?

👉Equivalent to constructors in OOP terminology, __init__ is a reserved method in Python classes. The __init__ method is called automatically whenever a new object is initiated. This method allocates memory to the new object as soon as it is created. This method can also be used to initialize variables.

Syntax

class Human:
# init method or constructor
def __init__(self, age):
self.age = age
# Sample Method
def say(self):
print('Hello, my age is', self.age)
h= Human(22)
h.say()

Output:

Hello, my age is 22

Share and Support
@Python_Codes

Читать полностью…

Python Codes

Inheritance in Python with an example?

👉As Python follows an object-oriented programming paradigm, classes in Python have the ability to inherit the properties of another class. This process is known as inheritance. Inheritance provides the code reusability feature. The class that is being inherited is called a superclass or the parent class, and the class that inherits the superclass is called a derived or child class. The following types of inheritance are supported in Python:

👉
Single inheritance: When a class inherits only one superclass

👉Multiple inheritance: When a class inherits multiple superclasses

👉Multilevel inheritance: When a class inherits a superclass, and then another class inherits this derived class forming a ‘parent, child, and grandchild’ class structure

👉Hierarchical inheritance: When one superclass is inherited by multiple derived classes

Share and Support
@Python_Codes

Читать полностью…

Python Codes

Time complexity in above Picture

Fibonacci Number using Dynamic Programming:

CODE:

calculated = {}

def fib(n):
if n == 0: # base case 1
return 0
if n == 1: # base case 2
return 1
elif n in calculated:
return calculated[n]
else: # recursive step
calculated[n] = fib(n-1) + fib(n-2)
return calculated[n]

Share and Support
@Python_Codes

Читать полностью…

Python Codes

Dynamic Programming:

👉 In simple words, the concept behind dynamic programming is to break the problems into sub-problems and save the result for the future so that we will not have to compute that same problem again.

👉 Dynamic programming is a problem-solving technique for resolving complex problems by recursively breaking them up into sub-problems, which are then each solved individually. Dynamic programming optimizes recursive programming and saves us the time of re-computing inputs later.

Share and Support
@Python_Codes

Читать полностью…

Python Codes

#numpy

NumPy

Broadcasting


Broadcasting describes how NumPy automatically brings two arrays with different shapes to a compatible shape during arithmetic operations. Generally, the smaller array is “repeated” multiple times until both arrays have the same shape. Broadcasting is memory-efficient as it doesn’t actually copy the smaller array multiple times.

Code:

import numpy as np

A = np.array([1, 2, 3])
res = A * 3 # scalar is broadcasted to [3 3 3]
print(res)

Output:
# [3 6 9]

Share and Support
@Python_Codes

Читать полностью…
Subscribe to a channel