Python tips 100

0) explore methods of the random library by using dir(module) and help(module)
dir(random) and help(random)

1) print("\a"): (Make print sing)

2) Dictionary Merge: (Python Syntax Show Off)
use ** notation for **kwargs-like objects (values with names like dictionaries) to merge dictionaries  conveninently.
d1 = {"A": 10, "B": 20, "C": 30}
d2 = {"X": 100, "Y": 200, "Z": 300}
d3 = {**d1, **d2}
print(d3)
{'A': 10, 'B': 20, 'C': 30, 'X': 100, 'Y': 200, 'Z': 300}

3) Proper File Paths: (Handling Paths)
r'' standing for raw string, r in front of the string quotes ensure that file paths don’t get confused between Python and system settings.
f = r'/home/kali/test.py'
data = open(f, "r")
print(data.read())

4) Big Number Readability: (Millions and Billions)
you can separate zeros with underscore (_)
print(1_000_000)
print(1_000_000 +1)
1000000
1000001

5) Let the code draw: (Python Turtle Drawing)
import turtle

6) Chain Operators: (Larger Than and Smaller Than)
You can chain comparison operators in Python as following:
n = 10
result = 1 < n < 20
True

7) Pretty Print: (Pprint)
>>> import pprint
>>> data = {'place_id': 259174015, 'licence': 'Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright', 
...         'osm_type': 'way', 'osm_id': 12316939, 'boundingbox': ['42.983431438214', '42.983531438214', '-78.706880444495', 
...         '-78.706780444495'], 'lat': '42.983481438214326', 'lon': '-78.70683044449504', 'display_name': '''230, Fifth Avenue,
...         Sheridan Meadows, Amherst Town, Erie County, New York, 14221, United States of America''', 
...         'class': 'place', 'type': 'house', 'importance': 0.511}
>>> pprint.pprint(data, indent=3)
{  'boundingbox': [  '42.983431438214',
                     '42.983531438214',
                     '-78.706880444495',
                     '-78.706780444495'],
   'class': 'place',
   'display_name': '230, Fifth Avenue,\n'
                   '        Sheridan Meadows, Amherst Town, Erie County, New '
                   'York, 14221, United States of America',
   'importance': 0.511,
   'lat': '42.983481438214326',
   'licence': 'Data © OpenStreetMap contributors, ODbL 1.0. '
              'https://osm.org/copyright',
   'lon': '-78.70683044449504',
   'osm_id': 12316939,
   'osm_type': 'way',
   'place_id': 259174015,
   'type': 'house'}
>>> 

8) Getting rid of unwanted characters: (left strip, right strip and just strip)
get rid of whitespaces or any specific character using strip methods in Python, use either plain strip for both sides, lstrip for the left side and rstrip for the right side only.
str="+++World Cup+++"
str.strip()
print(str)
World Cup

9) Merging strings: (join method)
>>> lst=["Nepal", "Bhutan", "Korea", "Vietnam"]
>>> str=",".join(lst)
>>> str
'Nepal,Bhutan,Korea,Vietnam'

10) Versatile Arithmetic Operators: (Multiply Lists & Add Strings)
str1="hey"
str2=" there"
str3="\n"
print(str1+str2)
print(str3*5)
hey there
\n\n\n\n\n

11) Floor Division: (Keep the change)
print(1000 // 400)
print(1000 / 400)
2
2.5

12) Negative Indexing: (Accessing from the end)
name="Crystal"
print(name[0])
print(name[-1])
print(name[0:3])
print(name[-1:-4:-1])
C
l
Cry
lat

13) Break up strings: (Split Method)
str = "Hello World"
a = str.split(" ")
print (a)
["Hello", "World"]

14) When the code is too fast: (Make Python Sleep)
import time
time.sleep(secs)

15) Reverse data: (Slice Notation)
str="Californication"
a=str[::-1]
print(a)
noitacinrofilaC

16) Reverse data: (Reversed Function & Reverse Method)
Reversed function and reverse method can only be used to reverse objects in Python. But there is a major difference between the two:
    reversed function can reverse and iterable object and returns a reversed object as data type.
    reverse method can only be used with lists as its a list method only.
Check out 3 examples below:
#1
lst=["earth","fire","wind","water"]
lst.reverse()
print(lst)
['water', 'wind', 'fire', 'earth']

#2
lst=["earth","fire","wind","water"]
a=reversed(lst)
print(a)
print(list(a))
<reversed object at 0x000001C247364C88>
['water', 'wind', 'fire', 'earth']
#3
str="Californication"
a=reversed(str)
print(("".join(a)))
noitacinrofilaC

17) Multi Assignments: (One-Liner)
a = [1000, 2000, 3000]
x, y, z = a
print(z)
3000

18) Code Sections: (Spyder)
#%% Creating Code Sections in your IDE (Spyder)

19) Remove Duplicates: (set function)
#1
lst=[1,2,2,2,2,3,4,4,5,6,7]
a=set(lst)
print(a)
{1, 2, 3, 4, 5, 6, 7}
print(type(a))

#2
lst=[1,2,2,2,2,3,4,4,5,6,7]
a=list(set(lst))
print(a)
print(type(a))
{1,2,3,4,5,6,7}
<class 'list'>

20) Python Working Directory: (os.getcwd())
>>> import os
>>> dirpath = os.getcwd()
>>> dirpath
'/home/kali'

20) Python Working Directory: (os.chdir())
import os 
os.chdir(r'/home/kali/Desktop')

print(os.getcwd())
/home/kali/Desktop

22) Printing libraries: (To get their directiories)
import pandas
print(pandas)

23) Membership Operators: (in & not in)
lst = "10, 50, 100, 500, 1000, 5000"
for i in lst:
    if i == str(0):
        print(i, end="|")
0|0|0|0|0|0|0|0|0|0|0|0|

24) Advanced Print: (sep parameter)
str1="bluemoon"
str2="geemayl.com"
print(str1, str2,sep="@")
bluemoon@geemayl.com

25) Advanced Print: (end parameter)
print("one" , end ="," )
print("two", end =",")
print("three")
one, two, three

26) Triple quotes: (Multiline Strings)
”’some text here”’

27) List Comprehension: ()
rng = range(1200, 2000, 130)
lst = [i for i in rng]
print(lst)

lst1=[44,54,64,74,104]
lst2 = [i+6 for i in lst1]
print(lst2)

lst1=[2, 4, 6, 8, 10, 12, 14]
lst2 = [i**2 for i in lst1]

lst1=[2, 4, 6, 8, 10, 12, 14]
lst2 = [i**2 for i in lst1 if i**2>50]

dict={"Sedan": 1500, "SUV": 2000, "Pickup": 2500, "Minivan": 1600, "Van": 2400, "Semi": 13600, "Bicycle": 7, "Motorcycle": 110}
lst = [i.upper() for i in dict if dict[i]<5000]
print(lst)

28) Dict Comprehension: ()
lst=["NY", "FL", "CA", "VT"]
dict = {i:i for i in lst}
print(dict)

>>> rng = range(100, 160, 10)
>>> dict = {i:i/100 for i in rng}
>>> print(dict)
{100: 1.0, 110: 1.1, 120: 1.2, 130: 1.3, 140: 1.4, 150: 1.5}
>>> 

dict1={"NFLX":4950,"TREX":2400,"FIZZ":1800, "XPO":1700}
dict2 = {i:dict1[i] for i in dict1 if dict1[i]>2000}
print(dict2)
{'NFLX': 4950, 'TREX': 2400}

29) Partial assignments: (List Unpacking)
#1
lst = [10, 20, 30, 40]
a, *b = lst
print(a)
print(b)

10
[20,30,40]

#2
lst = ["yellow", "gray", "blue", "pink", "brown"]
a, *b, c = lst
print(a)
print(b)
print(c)

"yellow"
["gray", "blue", "pink"]
"brown"

30) Ordered Dictionaries: (from collections)
import collections
d = collections.OrderedDict()
d[1] = 100
d[2] = 200
print(d)

OrderedDict([(1, 100), (2, 200)])

31) Permutations: (from itertools)
import itertools
lst = [1,2,3,4,5]
print(len(list((itertools.permutations(lst)))))
for i in itertools.permutations(lst):    
    print (i, end="\n")

120
(1, 2, 3, 4, 5)
... ... 
(5, 4, 3, 2, 1)

import itertools
lst = [1,2,3,4,5]
print(len(list((itertools.permutations(lst)))))
for i in itertools.permutations(lst):
     print (''.join(str(j) for j in i), end="|")

12345|12354|12435|12453|12534|12543|13245|13254|13425|13452|13524|13542|14235|14253|14325|14352|14523|14532|15234|15243|15324|15342|15423|15432|21345|21354|21435|21453|21534|21543|23145|23154|23415|23451|23514|23541|24135|24153|24315|24351|24513|24531|25134|25143|25314|25341|25413|25431|31245|31254|31425|31452|31524|31542|32145|32154|32415|32451|32514|32541|34125|34152|34215|34251|34512|34521|35124|35142|35214|35241|35412|35421|41235|41253|41325|41352|41523|41532|42135|42153|42315|42351|42513|42531|43125|43152|43215|43251|43512|43521|45123|45132|45213|45231|45312|45321|51234|51243|51324|51342|51423|51432|52134|52143|52314|52341|52413|52431|53124|53142|53214|53241|53412|53421|54123|54132|54213|54231|54312|54321|

32) Factorial: (user function)
n = 159
for i in range(1, n + 1):
    if n % i == 0:
        print(i)

1
3
53
159

33) clear console: (Spyder)
Simply type clear 

34) N largest & N smallest: (Standard heapq library)
import heapq

grades = [5, 78, 6, 30, 91, 1005.2, 741, 1.9, 112, 809.5]
print(heapq.nlargest(2, grades))
print(heapq.nsmallest(5, grades))

[1005.2, 809.5]
[1.9, 5, 6, 30, 78]

35) Make it immutable: (frozenset)
lst = ["June", "July", "August"]
lst[0]="May"
print(lst)

['May', 'July', 'August']

i_lst=frozenset(lst)
print(i_lst)
i_lst[0] = "June"

TypeError: 'frozenset' object does not support item assignment

Bonus) Short library names: (import as)
import matplotlib as mpl
import pandas as pd
import numpy as np
import statsmodels as sm
import tensorflow as tf
import seaborn as sb

36) A beautiful counter: (itertools / count)
###1
from itertools import count

index = count()
print(next(index))
print(next(index))
print(next(index))
print(next(index))
print(next(index))
print(next(index))

0
1
2
3
4
5

###2
from itertools import count

c = count()

for i in range(20):
    print(next(c), end="|")

0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|

37) A different kind of counter: (collections / counter)

from collections import Counter
counter = Counter(['red', 'red', 'red', 'blue', 'yellow'])
print(counter)

Counter({'red': 3, 'blue': 1, 'yellow': 1})

from collections import Counter
counter = Counter(red=1, blue=3, yellow=2)
print(counter)
print(list(counter))
print(dict(counter))

Counter({'blue': 3, 'yellow': 2, 'red': 1})
['red', 'blue', 'yellow']
{'red': 1, 'blue': 3, 'yellow': 2}

38) Extracting nested data: (itertools)

import itertools

a = [[10, 21, 33], [45, 57], [69]]
for i in (itertools.chain.from_iterable(a)):
    print(i)
    
print(list(itertools.chain.from_iterable(a)))

10
21
33
45
57
69

[10, 21, 33, 45, 57, 69]

39) Unpacking: (star notation method)
###
a = [1,1,1,2,3,75,4,5,6]
print(max(*a))
###
import itertools

def lister(*x):
    for i in x:
        print(i, end="|")

a = [1,1,1,2,3,75,4,5,6]
lister(*a)

40) For loop + else: (for else)

for i in range(5):
    print(i)
else:
    print("yes")

0
1
2
3
4
yes


for i in range(5):
    print(i)
    if i == 2:
        break
else:
    print("yes")

0
1
2

41) Swapping Dictionary Key & Values: (zip method)

a = {1:11, 2:22, 3:33}

b = zip(a.values(), a.keys())
c = dict(b)

print(c)

{11: 1, 22: 2, 33: 3}

a = {1:11, 2:22, 3:33}
b = dict(zip(a.values(), a.keys()))

print(c)

42) Swapping Dictionary Key & Values: (dict comprehension method)

a = {1:11, 2:22, 3:33}
b = (a.items())
c = {i:j for j,i in b}
print(c)
{11: 1, 22: 2, 33: 3}

a = {1:11, 2:22, 3:33}
b = {i:j for j,i in a.items()}
print(c)

43) Conditional Statements: (One-Liner)

a=10
c = True if a**2 > 100 else False
print(c)

False

44) Lambda: (One-Liner)

a = lambda x: x**2
print(a(5))

45) Returning multiple values: (return statement)

def loc_id(city, county, state):
    return city, county, state

a = loc_id("LA", "OC", "FL")

print(a)

46) Function return assignments: (One-Liner)

def loc_id(city, county, state):
    return city, county, state

a,b,c = loc_id("LA", "OC", "FL")

print(a)

47) Anagram Checker: (sorted function)

def anagram_checker(str1, str2):
    return sorted(str1) == sorted(str2)

print(anagram_checker('vases', 'saves'))
print(anagram_checker('cola', 'coal'))
print(anagram_checker('cake', 'take'))

True
True
False

48) Anagram Checker: (Counter)

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

print(anagram_checker('senator', 'treason'))
print(anagram_checker('section', 'notice'))
print(anagram_checker('relation', 'oriental'))

True
False
True

49) Enumerate: (Enumerated Iterables)

str="Whatsup"
l=enumerate(str)
print(list(l))

[(0, 'W'), (1, 'h'), (2, 'a'), (3, 't'), (4, 's'), (5, 'u'), (6, 'p')]


str=["sun", "moon", "mars", "venus"]
l=enumerate(str,100)
print(list(l))

[(100, 'sun'), (101, 'moon'), (102, 'mars'), (103, 'venus')]

50) Most Frequent Value: (max and set)

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

4

51) Advanced Python function parameters: (Lambda, Comprehension, Conditionals)

result = 0
for i in range(10):
    if i % 2 == 0:
        result += i
print(result)

You can do this:
sum(i for i in range(10) if i % 2 == 0)

52) Creating Copies: (list copy method & dict copy method)

lst1 = ["yellow", "gray", "brown"]
lst2 = lst1.copy()

dict1 = {'Fruit': 'Melon', 'Dessert': "Ice cream"};
dict2 = dict1.copy()

53) Creating Copies: (Slicing)

lst1 = ["yellow", "gray", "brown"]
lst2 = lst1[:]
Please note that immutable objects such as string and tuples don’t have copy methods since they will always refer to the same memory ID as long as 2 strings or 2 tuples have the same exact values.

54) Copy Library: (Deepcopy)

import copy
lst1 = ["yellow", "gray", "brown"]
lst2 = copy.deepcopy(lst1)

55) Swap Values: (One-Liner)
a=10
b=20
a,b = b,a

56) Encoding: (utf-8)
UnicodeDecodeError: ‘charmap’ codec can’t decode
open(filename, encoding=’utf8′)

57) Ascii Conversions: (ord)

print(ord("K"))

58) Ascii Conversions: (chr)

print(chr(111))

59) Identity Operators: (is & not is)

a=["Antarctica"]
b=["Antarctica"]
    
c=a
print(a is b)
print(a is c)
print(a is not b)

False
True
True

60) with open as: (work on open file)

with open('research.csv') as f:
    data = csv.reader(f)
    for i in data:
        print(i)

61) Bin for bits: (And a little bit of computer history)

print(bin(5))
0b101

62) Bit Length: (How many bits do you need?)

>>> a=4
>>> b=a.bit_length()
>>> print(b)
3

63) to_bytes: (Numbers to Bytes)

1 nibble = 1 hex = 4 bits = 2^4 values
1 byte = 2 nibbles = 8 bits = 2^8 values

a=15
b=a.to_bytes(2, byteorder="big")
print(b)
b'\x00\x0f'

c=888
d=c.to_bytes(2, byteorder="big")
print(d)

b'\x00\xde'

64) Vim: (coolest code editor)
https://holypython.com/how-to-use-vim-editor-to-write-python-code/

65) Random Numbers: (import random)

randint for an integer between lower and upper limits:
import random
a=random.randint(33, 333)
print(a)
263

randrange(start, stop, steps)
import random
a=random.randrange(0, 50, 8)
print(a)

random() will return a float value between 0 and 1
import random
a=random.random()
print(a)

66) Opening a Web Page: (webbrowser library)

import webbrowser
f=r'https://www.google.com'
webbrowser.open(f)

67) Deque: (Sequences with double ends)

import collections
a = collections.deque()

a.append(100)
a.appendleft(4)
print(a)
deque([4, 100])

a.extend([200, 300, 400])
a.extendleft([3, 2, 1])
print(a)
deque([1, 2, 3, 4, 100, 200, 300, 400])

a.pop()
a.popleft()
print(a)
deque([2, 3, 4, 100, 200, 300])

a.rotate(3)
print(a)
deque([100, 200, 300, 2, 3, 4])

a.rotate(-1)
print(a)
deque([200, 300, 2, 3, 4, 100])

68: Greatest common divisor: (math library)

import math
print(math.gcd(65,780))
print(math.gcd(6,40))
print(math.gcd(12,40))

65
2
4

69) Play Audio: (os library)

import os
f="Track01.mp3"
os.system(f)

70) Jupyter Notebook (Shortcuts & Line Magic)

Command Mode
Enter 	enter edit mode
Shift Enter 	run section, skip to next section
Ctrl Enter 	run section
üp arrow, down arrow  or k , j 	selects cell above or below
a , b 	inserts cell above or below
x , c , v 	cut , copy , paste cell
Shift v 	paste cell above
z 	undo last cell deletion
d, d 	delete selected cell
Shift m 	merge cell below
Ctrl s 	saves
Edit Mode
Tab 	code completion or indent
Shift Tab 	tooltip
Ctrl ] 	indent
Ctrl [ 	deindent
Ctrl a 	selects all
Ctrl z 	undo
Ctrl Shift z 	redo
Jupyter Notebook Magic
%matplotlib inline 	allows graphic output within notebook
%%timeit Tab 	to measure the performance of processes (explained in #78 also)
%cls 	clears the screen
%cd 	to change the directory
%paste 	pastes from the clipboard
%source 	displays the source code of an object

71) Annotated Assignment Statement: (:)

day: str = 'Saturday'
print(day)
'Saturday'

lst: list = [1,2,3]
print(lst)
[1,2,3]

#older implementation 
day= 'Saturday' #str
print(day)
lst= [1,2,3] # list
print(lst)

72) Yield Statement: ()

def f1(a):
    yield a
    yield a**2
    yield a**3
    
print (f1(5))
<generator object f1 at 0x00000275EF339AC8>

for i in f1(5):
    print (i)    
5
25
125

def f2(b):
    for j in range(b):
        yield j

for i in f2(5):
    print(i)

0
1
2
3
4

73) News brought to you by: (Python Newspaper)

pip install newspaper

import newspaper
paper = newspaper.build('http://theatlantic.com')
for article in paper.articles:
    print(article.url)

from newspaper import Article

url = 'https://www.theatlantic.com/ideas/archive/2020/06/daca-activism/613213/'
article = Article(url)

article.download()
article.parse()


print(article.text)
print(article.authors)
print(article.publish_date)
print(article.images)
print(article.title)
print(article.tags)
print(article.summary)

74) Geopy: (Work on Open File)

from geopy.geocoders import Nominatim
geolocator = Nominatim(user_agent="HiApp")
location = geolocator.geocode(" 230 Fifth Ave, New York")
print(location.address)

230, Fifth Avenue, Sheridan Meadows, Amherst Town, Erie County, New York, 14221, United States of America

75) sh: (Shell scripts and bash commands)

import sh
sh.google_chrome("http://google.com”)

Here are some other ideas:

import sh
sh.whoami()
sh.pwd()
sh.mkdir('foldername')
sh.touch('filename.txt')
sh.echo('Hello World')

76) Decorators: (Augmenting functions without modifications)

def adder(a, b): 
    return a+b
print(adder(2, 3))
5

def decoten(func): 
    def times10(x, y): 
        return func(x*10, y*10) 
    return times10

@decoten
def adder(a, b): 
    return a+b 
print(adder(2,3))
50

77: Memory Optimization: (__slots__)

class Team:
    __slots__ = ["name", "score"]
    def __init__(self, name, score):
        self.name = name
        self.score = score
        

a=Team("Real Madrid", 5)
print(a.name, a.score, sep=" : ")

Real Madrid : 5

78) Time it: (Time Processes)

import timeit

lst1='''list(range(1000))'''
lst2='''[i for i in range(1000)]'''

x=timeit.timeit(lst1)
y=timeit.timeit(lst2)

print(x, y, sep="------")

11.646945999999843 ------- 27.643676500000083

79) Virtual env: (Managing Dependencies)

pip install virtualenv

virtualenv environment1

you can also activate and deactivate a virtual environment simply by typing:

activate environment1
deactivate

80) Groupby from itertools: (Grouping Python Data)

from itertools import groupby

lst = [("car", "Ferrari"), ("car", "Renault"), ("country", "France"), ("country", "New Zealand"), ("fruit", "Kiwi")]

for i, group in groupby(lst, lambda x: x[0]):
    for j in group:
        print ("{} is a {}.".format(j[1], val))
    print()

Ferrari is a fruit.
Renault is a fruit.

France is a fruit.
New Zealand is a fruit.

Kiwi is a fruit.

81) Transposing Data: (zip method)

mat = [[1, 2, 3], [1000, 2000, 3000]]
zip(*mat)

[(1, 1000), (2, 2000), (3, 3000)]

82) Working with Zipped files: (ZipFile Library)

from zipfile import ZipFile

f = ZipFile("myarchive.zip", "r")
f = ZipFile("myarchive.zip", "w")

    Get file names: You can have a list of all the files’ names returned using namelist() method

from zipfile import ZipFile

f = ZipFile("myarchive.zip", "r")
print(f.namelist())

['app.html', 'credits.html', 'app.css', 'auth.css', 'bridge.css', 'history.css', 'd3dcompiler.dll']

    Extract files:

from zipfile import ZipFile

f = ZipFile("myarchive.zip", "r")
f.extractall("directory")

    Read & Write:

from zipfile import ZipFile

f = ZipFile("myarchive.zip", "r")
a=f.read(r"FF/app.html")
print(a)

    Please note that during the write operation zipfile is specifically opened with “w” parameter.

from zipfile import ZipFile

with ZipFile("myarchive.zip", "w") as f:
    f.write("pricelist.txt")
    f.write("deliveries.xls")

83) Time library: (More Time Functions)
import time

time_now=time.strftime("%H:%M:%S",time.localtime())
print(time_now)

date_now=time.strftime("%Y-%b-%d",time.localtime())
print(date_now)
21:47:43
2020-Jun-24

84) getsizeof: (Sys Library)

import sys
a="Paris"
b=sys.getsizeof(a)
print(b)

54

85) Named Tuples: (From Collections Library)

from collections import namedtuple

flights = namedtuple("flight", "price, distance")
US = flights(2000,5000)
Iceland = flights(500,500)
France = flights(1000,1000)

print(France.distance)
1000

86) Animated Charts: (Save as Gif or Mp4)

import random
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

fig = plt.figure(figsize=(15,15))

x,y = [], []
index= count()
def animate(i):
    x.append(next(index))
    y.append(random.randint(2,20))
    plt.style.use("ggplot")    
    plt.plot(x,y)

ani = FuncAnimation(fig, animate, interval=300)
plt.show() 

87) All or any: (or & and Alternatives)


any([False, False, False])
all([False, True, True])
any([True, False, False])
any([False, False, True])
all([True, True, True])

False
False
True
True
True

88) Recursive Functions: (Functions calling themselves)

Fib(n-2) + Fib(n-1) = Fib(n)
0 | 1 | 1 | 2 | 3 | 5 | 8 | 13 | 21 | 34 | 55 ….

def fibo(x):
    
    if x <= 1:
        return x
    else:
        return fibo(x-1) + fibo(x-2)
    
for i in range(40):
    print(fibo(i), end=" || ")
0 || 1 || 1 || 2 || 3 || 5 || 8 || 13 || 21 || 34 || 55 || 89 || 144 || 233 || 377 || 610 || 
987 || 1597 || 2584 || 4181 || 6765 || 10946 || 17711 || 28657 || 46368 || 75025 || 121393 || 
196418 || 317811 || 514229 || 832040 || 1346269 || 2178309 || 3524578 || 5702887 || 9227465 || 
14930352 || 24157817 || 39088169 || 63245986 || 

89) Cache results with decorators: (Efficient Functions)
from functools import lru_cache

@lru_cache(maxsize=None)
def fibo(x):
    if x <= 1:
        return x
    else:
        return fibo(x-1) + fibo(x-2)

for i in range(50):
    print(fibo(i), end="|")

print("\n\n", fibo.cache_info())

90) Textblob: (Sentiment Analysis)
from textblob import TextBlob

f = r"c://Users/USA/Desktop/asd.txt"
file = open(f, "r", encoding="utf8")
data= (file.read())

blob = TextBlob(data)

b=blob.sentences
print(b[0])

lots of convenient methods and attributes included such as:

    .tags
    .noun_phrases
    .sentiment
    .sentiment.polarity
    .words
    .sentences
    .lemmatize (grouping similar words for analysis based on context)
    .definition
    .correct()
    .spellcheck()
    .words.count()
    .ngrams()

91) Kwargs: (Arguments for named sequences)

def payloads(**kwargs):
    for key, value in kwargs.items():
        print( key+" |||", float(value)*1000)

payloads(NavSat1 = '2.8', BaysatG2 = '5')
NavSat1 ||| 2800.0
BaysatG2 ||| 5000.0

def payloads(**kwargs):
    for key, value in kwargs.items():
        print( key+" |||", float(value)*1000)

sats={"Tx211":"2", "V1":"0.65"}
payloads(**sats)
Tx211 ||| 2000.0
V1 ||| 650.0

92) Compile a regex formula: (Advanced Regex)

import re

str='''Chuck Norris can divide by zero.
When Chuck Norris falls in water, Chuck Norris doesn't get wet. Water gets Chuck Norris.
Chuck Norris once visited the Virgin Islands. They are now The Islands.'''

result2 = (re.match('[A-Z][a-z]*\s\S*', str))
print((result2))

import re

str='''Chuck Norris can divide by zero.
When Chuck Norris falls in water, Chuck Norris doesn't get wet. Water gets Chuck Norris.
Chuck Norris once visited the Virgin Islands. They are now The Islands.'''

query = re.compile('[A-Z][a-z]*\s\S*')
result1 = (query.match(str))

print((result1))

93) Create a File Server: (A Surprising One Liner)
python -m http.server 8000

94) Enum Class: (Members with unique ID values)

from enum import Enum

class sports(Enum):
    skiing = 0
    soccer = 1
    running = 2
    football = 3
    golf = 4
    swimming = 5
    
    
print(sports.golf)
print(repr(sports.golf))

sports.golf
<sports.golf: 4>


for i in sports():
    print(i)

<sports.skiing: 0>
<sports.soccer: 1>
<sports.running: 2>
<sports.football: 3>
<sports.golf: 4>
<sports.swimming: 5>

95) Connect to Database: (SQLite)
import sqlite3

q = sqlite3.connect('Mydatabase.db')
cursor = q.cursor()

cursor.execute('SELECT id, name FROM Prices')
data = cursor.fetchall()
for i in data:
    print(i)

cursor.close()

q.close()

96) StringIO, cStringIO and BytesIO: (Python Streams)

import StringIO

str = "Hello World"
file = StringIO.StringIO(str)

print (file.read())

97) Work with gzip files in Python: (gzip library)
import gzip

str = b"Hello World"
c_str = gzip.compress(str)

import gzip
str = "Hello World"
str = bytes(str, "utf8")
c = gzip.compress(str)
print(c)

import gzip

lst = ["kiwi","apple","banana"]
lst = str(lst)
lst = bytes(lst, "utf8")
c=gzip.compress(lst)
print(c)

import gzip
dec_lst = gzip.decompress(c_lst)

with gzip.open("textfile.txt.gz", "rb") as file:
	data = file.read()

98) Memory Management: (getrefcount method)
import sys
import matplotlib.pyplot as plt
 
#string with all character letters
str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
x_ax = [sys.getrefcount(i) for i in str]
y_ax = range(len(str))
Graph = plt.figure(figsize=(250,150))

plt.bar(y_ax, x_ax, align='center', color="orange")
plt.xticks(y_ax, str)

plt.xlabel("Character")
plt.ylabel('sys.getrefcount(str)')
 
Graph.show()

99) os.environ: (environment variables)
import os
print(os.environ)

100) Serialization: (pickle & Json)


import pickle

lst = ["LAX", "LGA", "DEN", "SFO", "JFK", "MIA"]
a = pickle.dumps(lst)

print(a)

b'\x80\x03]q\x00(X\x03\x00\x00\x00LAXq\x01X\x03\x00\x00\x00LGAq\x02X\x03\x00\x00\x00DENq\
x03X\x03\x00\x00\x00SFOq\x04X\x03\x00\x00\x00JFKq\x05X\x03\x00\x00\x00MIAq\x06e.'

print(pickle.loads(a))

['LAX', 'LGA', 'DEN', 'SFO', 'JFK', 'MIA']

Bonus) Abstract Base Classes: (ABC)
from abc import ABC, abstractmethod
 
class ClassAbstract(ABC):
 
    def __init__(self, val1):
        self.value1 = val1
    
    @abstractmethod
    def under_construction(self):
        pass

class DDD(ClassAbstract):

    def under_construction(self):
        return self.value1
    
data1 = DDD(10)

print(data1.under_construction())



Navigation