Python Codes
6.29K subscribers
51 photos
1 file
86 links
This channel will serve you all the codes and programs which are related to Python.

We post the codes from the beginner level to advanced level.
Download Telegram
๐Ÿ•น Want to work in the Gaming industry?

We collected jobs for python ๐Ÿ developers in the Gaming industry in India ๐Ÿ‡ฎ๐Ÿ‡ณ
Click the link below to see them in our telegram channel.

๐Ÿ‘‰ Click here: https://t.me/+ORGwFAgg2HliZDNi
#Basics

Condition inside the print function

def is_positive(number):
print("Positive" if number > 0 else "Negative")



is_positive(-3)

Output:

Negative

Share and Support
@Python_Codes
#Basics

Convert a value into a complex number

print(complex(10, 2)) 

Output:
(10+2j)

Share and Support
@Python_Codes
If you want to contact us

Message to this account

Username: @Ping_TG
#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
#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
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
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
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
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
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
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
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
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
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
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
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
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
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
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