Python Codes
6.2K 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
#Basics

Find The Most Frequent Value In A List

Code:
test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4]
print(max(set(test), key = test.count))

Output:
4
Share and Support
@Python_Codes
#Basics

Check The Memory Usage Of An Object.

Code:
import sys
x = 1
print(sys.getsizeof(x))

Output:
28

Share and Support
@Python_Codes
#Basics

Checking if two words are anagrams

Code:
from collections import Counter
def is_anagram(str1, str2):
return Counter(str1) == Counter(str2)

# or without having to import anything
def is_anagram(str1, str2):
return sorted(str1) == sorted(str2)

print(is_anagram('code', 'doce'))
print(is_anagram('python', 'yton'))

Output:
True
False

Share and Support
@Python_Codes
#Basics

zip() function

When we need to join many iterator objects like lists to get a single list we can use the zip function. The result shows each item to be grouped with their respective items from the other lists.

Example:

Year = (1999, 2003, 2011, 2017)
Month = ("Mar", "Jun", "Jan", "Dec")
Day = (11,21,13,5)
print zip(Year,Month,Day)

Output:
[(1999, 'Mar', 11), (2003, 'Jun', 21), (2011, 'Jan', 13), (2017, 'Dec', 5)]

Share and Support
@Python_Codes
#Basics

Transpose a Matrix

Transposing a matrix involves converting columns into rows. In python we can achieve it by designing some loop structure to iterate through the elements in the matrix and change their places or we can use the following script involving zip function in conjunction with the * operator to unzip a list which becomes a transpose of the given matrix.

Example:

x = [[31,17],
[40 ,51],
[13 ,12]]
print (zip(*x))

Output:
[(31, 40, 13), (17, 51, 12)]

Share and Support
@Python_Codes
from turtle import *
color('red', 'green')
begin_fill()
while True:
forward(200)
left(170)
if abs(pos()) < 1:
break
end_fill()
done()

@python_codes
#Basics

The _ Operator

The _ operator might be something that you might not have heard of. Here _ is the output of the last executed expression. Letโ€™s check how it works.


Example:

>>> 2+ 3
5
>>> _ # the _ operator, it will return the output of the last executed statement.
>>> 5

Share and Support
@Python_Codes
#Basics

Swap keys and values of a dictionary

dictionary = {"a": 1, "b": 2, "c": 3}

reversed_dictionary = {j: i for i, j in dictionary.items()}

print(reversed)


Output:
{1: 'a', 2: 'b', 3: 'c'}

Share and Support
@Python_Codes
๐Ÿ•น 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