All Projects → dennyzhang → cheatsheet-python-A4

dennyzhang / cheatsheet-python-A4

Licence: other
📖 Advanced Python Syntax In A4

Programming Languages

python
139335 projects - #7 most used programming language

Projects that are alternatives of or similar to cheatsheet-python-A4

react-cheatsheets
Create and generate cheat sheets using React
Stars: ✭ 21 (-78.12%)
Mutual labels:  syntax, cheatsheets
laravel-or-abort
A trait to optionally abort a Laravel application
Stars: ✭ 54 (-43.75%)
Mutual labels:  syntax
Lexical syntax analysis
编译原理词法分析器&语法分析器LR(1)实现 C++
Stars: ✭ 173 (+80.21%)
Mutual labels:  syntax
Haskell Symbol Search Cheatsheet
Haskell/GHC symbol search cheatsheet
Stars: ✭ 243 (+153.13%)
Mutual labels:  syntax
Phpgrep
Syntax-aware grep for PHP code.
Stars: ✭ 185 (+92.71%)
Mutual labels:  syntax
berkeley-parser-analyser
A tool for classifying mistakes in the output of parsers
Stars: ✭ 34 (-64.58%)
Mutual labels:  syntax
React Ast
render abstract syntax trees with react
Stars: ✭ 160 (+66.67%)
Mutual labels:  syntax
colocat
Fegeya Colocat, Colorized 'cat' implementation. Written in C++17.
Stars: ✭ 14 (-85.42%)
Mutual labels:  syntax
nova-vue
Vue support for Nova editor.
Stars: ✭ 35 (-63.54%)
Mutual labels:  syntax
Chroma
A general purpose syntax highlighter in pure Go
Stars: ✭ 3,013 (+3038.54%)
Mutual labels:  syntax
Vim Cpp Modern
Extended Vim syntax highlighting for C and C++ (C++11/14/17/20)
Stars: ✭ 229 (+138.54%)
Mutual labels:  syntax
Ifmt
Inline expression interpolation for Rust.
Stars: ✭ 197 (+105.21%)
Mutual labels:  syntax
csaoid
Cheat Sheets and Other Interesting Documents
Stars: ✭ 20 (-79.17%)
Mutual labels:  cheatsheets
Vue Highlight.js
📜 Highlight.js syntax highlighter component for Vue.
Stars: ✭ 180 (+87.5%)
Mutual labels:  syntax
csscomplete.vim
Update the bult-in CSS complete function to latest CSS standard.
Stars: ✭ 61 (-36.46%)
Mutual labels:  syntax
Command
A library to build command line applications using PHP
Stars: ✭ 164 (+70.83%)
Mutual labels:  syntax
Clarifyjs
Create and Execute Chained Javascript Methods In Any Order You want
Stars: ✭ 227 (+136.46%)
Mutual labels:  syntax
LearningResources
A centralised hub for learner around the globe from A-Z. You can find collections of manuals, blogs, hacks, one liners, courses, other free learning-resources and more
Stars: ✭ 63 (-34.37%)
Mutual labels:  cheatsheets
nord-notepadplusplus
An arctic, north-bluish clean and elegant Notepad++ theme.
Stars: ✭ 112 (+16.67%)
Mutual labels:  syntax
explain-rs
A library which finds language features in rust code and provides resources on them.
Stars: ✭ 38 (-60.42%)
Mutual labels:  syntax

1 Python CheatSheet

linkedin
github
slack


PRs Welcome

File me Issues or star this repo.

See more CheatSheets from Denny: #denny-cheatsheets

1.1 Python Compact Coding

NameComment
Return if.. elsereturn val if i>0 else 0
Multiple assignmentl, r = 2, 3
Assign with check of nonea = b if b else 1
Assignmentsl[1]=l[0]=0
Swap valuesleft, right = right, left
List Comprehensions[x*x for x in range(1, 1001)]
List Comprehensionsl = [2, 3, 5]; [2*x for x in l if x>2]
Use zipfor a, b in zip(nums, nums[3:])
Build a listdp = [1] + [0]*3
Change interger to string in binarybin(num), f'{num:b}'=, ="{0:b}".format(num)
Sum a subarraysum(nums[0:k])
Sort list in descending ordersorted(nums, reverse=True)
Dictionary with defaultsm = collections.defaultdict(lambda: 1)
Loop with single statementwhile p.left: p = p.left
Print multiple valuesprint(x, y)
Get both index and itemfor i, ch in enumerate(["a", "b", "c"]): print(i, ch)
Mod negative(-2)%5
Compare valuesif 0<=i<n and 0<=j<m and grid[i][j]
if … returnif k == 0: return False
if… continueif index == icol: continue
List comprehensiveareas = [dfs(i, j) for i in range(m) for j in range(n) if grid[i][j]]
Python assertionassert [1,2]==[1,2]

1.2 Python Advanced: Concepts & Internals

NameComment
Python Global Interpreter LockFor Garbage Collection. A mutex controls of the global Python interpreter
Python tuples VS liststuple is immutable
Python nonlocal VS globalGithub: cheatsheet-python-A4/code/varNonlocalGlobal.py
Python For VS While LoopsThe for statement is used to iterate over the elements of a sequence
subprocess.run VS os.systemIn Linux, launch processes through shell or os.execvp
single quote VS double quoteGenerally double quotes for string; single quotes for regexp, dict keys, or SQL
Common reasons of python memory leakreference cycles, underly libaries/C extensions, lingering large objects not released
Example: Python cycle referenceGithub: cheatsheet-python-A4/code/exampleCycleReference.py
Passing function as an argument in PythonGithub: cheatsheet-python-A4/code/funcAsParameter.py
lambda/an anonymous function
Why no support for multi-line commentsLink: Python Multi-line Comments
Python callableprint(callable(1)), print(callable(lambda: 1))
Python long
Python Constants vs Literals
How functools.lru_cache works
Python yield
ReferenceLink: Python Design and History FAQ

1.3 List & Tuples

NameComment
Create a fixed size array[None]*5
Create a fixed size matrix/2D array[[sys.maxsize for j in range(2)] for i in range(3)]
Flatten 2D array into 1D array[a for r in matrix for a in r]
Iterate over a listfor v in l:
Iterate over a list with index+valfor i, v in enumerate(l):
zip two lists as onel = sorted(zip(nums, range(len(nums))))
Convert int array to a string=’ ‘.join([str(v) for v in [1, 2,3,4]])=
Extact columns from multi-dimensional array[row[1] for row in l]
Sort in descendingl=sorted([8, 2, 5], reverse=True)
Sort list by a lambda keyl=sorted([(‘ebb’,12),(‘abc’,14)], key=lambda x: x[1])
Sort list by a functionsorted(logs, key=getKey), LeetCode: Reorder Data in Log Files
In-place sortl.sort()
Find the index of one item[1,2,5,3].index(2)
Return all but lastlist[:-1]
The second last itemlist[-2] or list[~1]
Generate a-zmap(chr, range(ord('a'), ord('z')+1))
Convert from ascii to characterchr(ord('a'))
Reverse a list["ab", "cd", "ef"][::-1]
mapmap(lambda x: str(x), [1, 2, 3])
Copy a range to another rangenums1[:k+1] = nums2[:j+1]
append an elementarray.append(var)
insert elements to headarray.insert(0,var)
delete element by indexdel a[1]
list as stackitem = l.pop()
map/reducefunctools.reduce((lambda x, y: "%s %s" % (x, y)), l)
replace ith to jthlist[i:j] = otherlist
combine two listlist1 + list2
get sumsum(list)
unique listset(["Blah", "foo", "foo", 1, 1, 2, 3])
Insert to sorted listbisect.insort(l, 3)
Reverse a listl[::-1]
Print zip arrayprint(list(zip(l1, l2)))
ReferenceLink: Lists and Tuples in Python

1.4 String

NameComment
Reverse string‘hello world’[::-1]
Array to string’ ‘.join([‘a’, ‘b’])
Integer array to string’ ‘.join([str(v) for v in [1, 2, 3]])
Split string to array“hello, python”.split(“,”)
String to arraylist('abc')
Format to 2 digitsprint "%02d" % (13)
Capitalize string‘hello world’.capitalize()
Upper/lower string‘aBc’.upper(), ‘aBc’.lower()
Check if string represent integer‘123’.isdigit()
Check if string alphabetic‘aBc’.isalpha()
Check if string alphanumeric‘a1b’.isalnum()
Count substring‘2-5g-3-J’.count(‘-‘)
Remove tailing ‘0’‘0023’.rstrip(‘0’)
Remove leading ‘0’‘0023’.lstrip(‘0’)
Trip a string’ Hello ‘.strip()
Find location of substring‘abc’.find(‘d’)= (returns -1)
Find location of substring‘abc’.index(‘d’)= (raise exception)
Check whether substring“el” in “hello world”
Replace string‘ab cd’.replace(‘=’,=”)
Padding leading zero‘101’.zfill(10)
Padding whitespace to the left‘a’.ljust(10,’=’)
Padding whitespace to the right‘a’.rjust(10,’=’)
Format string“%s,%d,%s” % (“2012”, 12, “12”)

1.5 Stack & Queue

NameComment
Python deque as a stacks = collections.deque(), s.append(x), s.pop(), s[-1]
Python deque as a queues = collections.deque(), s.append(x), s.popleft(), s[0]
Implement a stack in PythonLink: Stack in Python. Leverage: list, collections.deque or queue.LifoQueue

1.6 Python Basic

NameComment
Install python3 in Ubuntuadd-apt-repository ppa:deadsnakes/ppa, apt install python3.7
Python constants
Python nested functionGithub: cheatsheet-python-A4/code/nestedFunction.py
Run python snippet from shellpython -c ‘import sys; print(sys.getdefaultencoding())’
What’s Python Literals
List all methods of a python object=dir(obj)=
How to check the type of one object?Use type function, e.g, type(enumerate([1, 2, 3]))

1.7 Common Errors

NameComment
Error: i++OK: i += 1
Error: b=trueOK: b=True
Error: i<len(A) && j<len(B):OK: i<len(A) and j<len(B):
Error: for i>=0 and j>=0:OK: while i>=0 and j>=0:
Error: ! fOK: not f
NameError: name ‘List’ is not definedfrom typing import List
Python float with high resolution

1.8 Pip - Python Package Management

NameComment
Check on installed python packagepip show simplejson
Search a packagepip search simplejson
Install and uninstall a packagepip install simplejson, pip uninstall simplejon
Install package with a specific versionpip install flake8==2.0
Show installation folder of a modulemodule.__file__, flask.__file__
Check on-line help for a modulehelp(module)
pip install -U simplejon
pip install -i http://pypi.python.jp flask

1.9 Integer

NameComment
max, minsys.maxsize, -sys.maxsize-1
min, maxmin(2, 3), max(5, 6, 2)
min with customized comparisionmin(a, b, key=lambda x: x*x-2*x+1)
generate rangefor num in range(10,20)
get asciiord('a'), chr(97)
print integer in binary“{0:b}”.format(10)

1.10 Dict/Hashmap & Set

NameComment
dict get first elementm[m.keys()[0]]
get by key with default valuem.get(x, -1)
Dictionary with defaultsm = collections.defaultdict(lambda: 1)
Dictionary with tuple defaultsd=collections.defaultdict(lambda: (0, 0))), d[0, 1]=(2, 3)
Use array as key in dictionaryConvert array to tuple: m[tuple(l)]=3
Check whether key in hashmapif k in m
Loop dictionary by keysfor k in m
Loop dictionaryfor k,v in m.items(), not for k,v in enumerate(m)
Intersection of two setslist(set(l1).intersection(set(l2)))
List to setset(list1)
Remove from sets.remove(2)
Deep copy dictimport copy; m2=copy.deepcopy(m1)
Remove the first from sets.pop()
Sort dict by valuessorted(dict1, key=dict1.get)
Convert a str to a dicteval("{\"createtime\":\"2013-07-16\"}")
Delete an element from a dictdel d[key]

1.11 Bit Operator

NameComment
modx % 2
shift leftx << 1; a << 2
shift righx >> 2
andx & y
complement~x
xorx ^ y
power2 ** 3
bool complementnot x
binary formatbin(5) (get 101)
count 1 inside binarybin(5).count('1')

1.12 File

NameComment
Append fileopen("/tmp/test.txt", "ab").write("\ntest:")
Write fileopen("/tmp/test.txt", "wab").write("\ntest:")
Read filesf.readlines()
Check fileos.path.exists("/tmp/test.txt")
ReferenceGithub: cheatsheet-python-A4/code/exampleFile.py

1.13 Math

NameComment
sqrtimport math; math.sqrt(5)
powerimport math; math.pow(2, 3)
logimport math; math.log(5, 2), log2(5)
randomrandom.randint(1, 10) 1 and 10 included
eval stringeval("2-11*2")

1.14 Networking

NameComment
Send http REST callpip install requests; r = requests.get(‘https://XX/XX’, auth=(‘user’, ‘pass’))
Start a simple HTTP serverpython -m SimpleHTTPServer <port_number>

1.15 Python Interoperate

NameComment
Run shell commandoutput = subprocess.run([“ls”, “-lt”, ”tmp”], stdout=subprocess.PIPE)
Get shell command outputoutput.stdout.decode('utf-8').split('\n')
Get shell return codeoutput.returncode, output.check_returncode()
Python trap linux signalGithub: cheatsheet-python-A4/code/exampleSignal.py

1.16 Queue/heapq

NameComment
Initialize min heapheapq.heapify(q)
heappush a tupleq=[]; heapq.heappush(q, (5, ‘ab’))
popprint (heapq.heappop(q))
first itemq[0]
print heapqprint list(q)
create a queuefrom collections import deque; queue = deque([1,5,8,9])
append queuequeue.append(7)
pop queue from headelement = queue.popleft()
ReferenceLink: Python Heapq

1.16.1 minheap & maxheap

import heapq

# initializing list
li = [5, 7, 9, 1, 3]

# using heapify to convert list into heap
heapq.heapify(li) # a minheap
heapq._heapify_max(li) # for a maxheap!

# printing created heap
print (list(li))

# using heappush() to push elements into heap
# pushes 4
heapq.heappush(li,4)

# printing modified heap
print (list(li))

# using heappop() to pop smallest element
print (heapq.heappop(li))

print (list(li))

1.17 Code snippets

  • Initialize Linkedlist from array
def initListNodeFromArray(self, nums):
    head = ListNode(None)
    prev, p = head, head
    for num in nums:
        pre = p
        p.val = num
        q = ListNode(None)
        p.next = q
        p = p.next
    pre.next = None
    return head
  • Print linkedlist
def printListNode(self, head):
    print("printListnode")
    while head:
        print("%d" % (head.val))
        head = head.next
  • Print Trie Tree in level order
def printTrieTreeLevelOrder(self, node):
    print("printTrieTreeLevelOrder")
    if node.is_word:
        print("Node is a word")
    queue = []
    queue.append(node)
    while len(queue) != 0:
        s = ''
        for i in range(len(queue)):
            node = queue[0]
            del queue[0]
            for child_key in node.children:
                s = '%s %s' % (s, child_key)
                queue.append(node.children[child_key])
        if s != '':
            print 'print level children: %s' % (s)
  • python sort with customized cmp function: -1 first
nums = [3, 2, 6]
def myCompare(v1, v2):
    return -1
sorted_nums = sorted(nums, cmp=myCompare)
print nums # [3, 2, 6]
print sorted_nums # [6, 3, 2]
  • Initialize m*n matrix
col_count, row_count = 3, 2
matrix = [[None for j in range(col_count)] for i in range(row_count)]
print matrix

1.18 Python Common Algorithms

NumCategory/TagExample
1#bfsLeetcode: Max Area of Island
2#dfsLeetCode: Surrounded Regions
3#binarysearchLeetCode: Search Insert Position
4#interval, #mergelistLeetCode: Interval List Intersections
5#twopointer, #arrayLeetCode: Reverse Words in a String II
6#twopointerLeetCode: Two Sum
7#backtracking, #subsetLeetCode: Subsets II
8#linkedlist, #presumLeetCode: Remove Zero Sum Consecutive Nodes from Linked List
9#unionfindLeetCode: Accounts Merge
10#trieLeetCode: Longest Word in Dictionary
11#stackLeetCode: Valid Parentheses
12#stackLeetCode: Reverse Substrings Between Each Pair of Parentheses
13#heapLeetCode: Top K Frequent Elements
14#baseconversionLeetCode: Base 7, LeetCode: Convert to Base -2
15#intervalLeetCode: Meeting Rooms II, LeetCode: My Calendar I
16#monotoneLeetCode: Daily Temperatures
17#knapsackLeetCode: Coin Change
18#sortbyfunctionLeetCode: Relative Sort Array
19#slidingwindowLeetCode: Longest Substring Without Repeating Characters
20#editdistance, #dynamicprogrammingLeetCode: Longest Common Subsequence
21#twopointer, #mergetwolistLeetCode: Merge Sorted Array
22#topologicalsortLeetCode: Course Schedule
23#bfs, bidirectional bfsLeetCode: Word Ladder
24#monotonicfunc, #binarysearchLeetCode: Kth Smallest Number in Multiplication Table
25#divideconquer, #recursiveLeetcode: Count of Smaller Numbers After Self
26python semaphoreLeetCode: Print Zero Even Odd

1.19 More Resources

License: Code is licensed under MIT License.

https://www.tutorialspoint.com/python_data_structure/index.htm

linkedin github slack
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].