Python - UzanR/UzCodingNewLife GitHub Wiki

bit_length()

Return the number of bits necessary to represent an integer in binary

n = 9 #1001
n.bit_length() = 4

isinstance(object, type)

Check object is type or not

n = 9.1
isinstance(n, int) #False

Shorten

temp = arr[i]
arr[i] = arr[i+1]
arr[i+1] = temp

shorten

arr[i],arr[i+1] = arr[i+1],arr[i]

String

str.strip() - Remove leading and ending space

str = ' hello uzanr'
str.strip()
>>> 'hello uzanr'

str.replace() - Remove all space

str = ' hello uzanr'
str.replace(' ','')
>>> 'hellpuzanr'

str.split() - Remove deplicated spaces

str = 'hello  uzanr'
" ".join(str.split())
>>> 'hello uzanr'

textwrap - split string with maxlength

str = 'This is an example feedback'
textwrap.wrap(feedback, size, break_long_words=False)
>>> ["This is","an","example","feedback"]

str.maketrans

key = "zabcdefghijklmnopqrstuvwxy"
password = "iamthebest"
table = str.maketrans("abcdefghijklmnopqrstuvwxyz", key)
return password.translate(table)
>>> "hzlsgdadrs"

Convert String to list unique character

document = "Todd told Tom to trot to the timber"
list(set(document))
>>> [' ', 'T', 'b', 'd', 'e', 'h', 'i', 'l', 'm', 'o', 'r', 't']

Number Formatting - "FORMAT".format(number)

|Number      |Format     |Output     |Description                                   |
|------------|-----------|-----------|----------------------------------------------|
|3.1415926   |{:.2f}     |3.14       |2 decimal places                              |
|3.1415926   |{:+.2f}	 |+3.14      |2 decimal places with sign                    |
|-1          |{:+.2f}    |-1.00      |2 decimal places with sign                    |
|2.71828     |{:.0f}	 |3          |No decimal places                             |
|5           |{:0>2d}    |05         |Pad number with zeros (left padding, width 2) |
|5           |{:x<4d}	 |5xxx       |Pad number with x’s (right padding, width 4)  |
|10          |{:x<4d}	 |10xx       |Pad number with x’s (right padding, width 4)  |
|1000000     |{:,}	 |1,000,000  |Number format with comma separator            |
|0.25	     |{:.2%}	 |25%        |Format percentage                             |
|1000000000  |{:.2e}	 |1.00e+09   |Exponent notation                             |
|13          |{:10d}	 |       13  |Right aligned (default, width 10)             |
|13          |{:<10d}	 |13         |Left aligned (width 10)                       |
|13          |{:^10d}	 |    13     |Center aligned (width 10)                     |

String Format

Multiple argument

s1 = "{0} is better than {1}".format("python","php")
>>> python is better than php

Name argument

s1 = "{user} uses {lang}".format(user="UzanR", lang="Python")
>>> UzanR uses Python

User format as function

myf = "My language is {lang}".format
myf(lang="python")
>>> My language is python

List

Append item to list

a = [1,2,3]
b = [4,5]
c = a.append(b)
>>> [1, 2, 3, [4, 5]]

Extend a list

a = [1,2,3]
b = [4,5]
c = a.extend(b)
>>> [1, 2, 3, 4, 5]

Array

odd element, even element

arr = [1,2,3,4,5,6]
arr[0::2]
>>> [1,3,5]
arr[1::2]
>>> [2,4,6]
-- normal way
count = 0
for i in L:
    if count%2 == 0:
        odd.append(i)
    else:
        even.append(i)
    count += 1
-- using emumerate
for count, i in emuerate(L):
    if count%2 == 0:
        odd.append(i)
    else:
        even.append(i)

Multi-dimension array

Create array

a = [[i*j for j in range(1,n+1)] for i in range(1,n+1)]

Access multi-dimension array

for arr1 in a:
    for arr2 in arr1:
        print(arr1)

Access using square brackets

for i in range(len(arr)):
    for j in range(i, len(arr[i)):
        print(arr[i][j])

Append an element to the end of list

a.append([10, 11, 12])
print(a)
Extend an element in the list
a[0].extend([10, 20, 30])
print(a)
Reserve the order of list
a[2].reverse()
print(a)

zip

Passing n argument

numbers = [1, 2, 3]
letters = ["a", "b", "c"]

zipped = zip(numbers, letters)

Convert to List

print("list(zip)")
print(list(zipped))
>>> [(1,"a"), (2,"b"), (3,"c")]

Convert to dict

print("dict(zip(arr1, arr2))")
print(dict(zip(numbers, letters)))
>>> {1:"a", 2:"b", 3:"c"}

Convert to set

print("set(zip(arr1, arr2))")
print(set(zip(numbers, letters)))
>>> {(1,"a"), (2,"b"), (3,"c")}

More than 3 lists

print([list(a) for a in zip([1,2,3], [4,5,6], [7,8,9])])

Map

Syntax

map(function_to_apply, list_of_inputs)

Sample

def fix(x):
    return x
result = [42, 239, 365, 50]
list(map(fix, result))
>>> [4, 23, 36, 5]

Filter

Syntax

filter(func, iterable)

Sample

scores = [66, 90, 68, 59, 76, 65]
def is_A_student(score):
    return score > 75
over_75 = list(filter(is_A_student, scores))
>>> [76, 90]

Python Generator

https://www.geeksforgeeks.org/generators-in-python/

itertools

product() - cartesian product, equivalent to a nested for-loop

product('ABCD', repeat = 2)
>>> AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD

permutations() - r-length tuples, all possible ordering, no repeated elements

permutations('ABCD', 2)
>>> AB AC AD BA BC BD CA CB CD DA DB DC

combinations() - r-length tuples, in sorted order, no repeated elements

combinations('ABCD', 2)
>>> AB AC AD BC BD CD

combinations_with_replacement() - r-length tuples, in sorted order, with repeated elements

combinations_with_replacement('ABCD', 2)
>>> AA AB AC AD BB BC BD CC CD DD
⚠️ **GitHub.com Fallback** ⚠️