• Stars
    star
    100
  • Rank 340,703 (Top 7 %)
  • Language
    Python
  • Created about 7 years ago
  • Updated over 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

📖 Advanced Python Syntax In A4

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

More Repositories

1

cheatsheet-kubernetes-A4

📖 Kubernetes CheatSheets In A4
Shell
1,851
star
2

cheatsheet.dennyzhang.com

Apply best practices via CheatSheets
Shell
649
star
3

kubernetes-yaml-templates

Kubernetes Yaml Templates
594
star
4

cheatsheet-jenkins-groovy-A4

📖 Groovy CheatSheet For Jenkins Usage In A4
Groovy
325
star
5

challenges-kubernetes

☁️ Challenges Your Kubernetes Skills And Knowledge
Shell
230
star
6

devops_public

🎩 DevOps Scripts
Shell
179
star
7

cheatsheet-gcp-A4

☁️ GCP gcloud, gsutil, etc.
110
star
8

code.dennyzhang.com

❓ Algorithms & Coding Problems
CSS
95
star
9

cheatsheet-docker-A4

📖 Docker CheatSheets In A4
Dockerfile
90
star
10

monitor-docker-slack

⏰ Get Slack Notifications, When Containers Run Into Issues
Python
71
star
11

challenges-cloudformation-jenkins

🏫 Challenges Your AWS And Cloudformation Skills By Solving Real Questions.
Shell
60
star
12

cheatsheet-golang-A4

📖 Advanced Golang Syntax In A4
Go
56
star
13

prepare-k8s-cka

📖 Preparation For Kubernetes CKA/CKAD Exam
51
star
14

cheatsheet-aws-A4

☁️ AWS CheatSheets In A4
48
star
15

cheatsheet-paper-A4

https://cheatsheet.dennyzhang.com/cheatsheet-paper-A4
46
star
16

Denny-s-emacs-configuration

🤖 Emacs shapes me to be a better programmer
Emacs Lisp
41
star
17

kubernetes-scripts

Handy kubernetes scripts for common scenarios
Shell
37
star
18

challenges-chef

📖 Challenges Your Chef Skills By Solving Real Questions.
Ruby
26
star
19

cheatsheet-git-A4

CheatSheet For Git & GitHub
25
star
20

developer-free-saas

🕸️ A curated list Of Free Web-based Tools For Developers
Shell
23
star
21

devops_jenkins

🤖 VisualOps via Jenkins jobs
21
star
22

architect.dennyzhang.com

☝️ Learn system design in a solid way
Shell
21
star
23

cheatsheet-tmux-A4

tmux/tmate Usage in A4
20
star
24

cheatsheet-vim-A4

Vim usage and personal knowledge base
18
star
25

cheatsheet-pks-A4

CheatSheet For PKS: Pivotal Kubernetes Service
Shell
16
star
26

popular-github-template

📗 Repo Template: Make Your GitHub Repos More Popular
16
star
27

cheatsheet-shell-A4

🏫 Examine your shell skills
Shell
16
star
28

xiaozibao

Your personal magzine, adjusted by your taste.
Objective-C
13
star
29

python-selenium

Use Python Selenium For GUI Automation Test
Python
11
star
30

cheatsheet-bosh-A4

📖 CheatSheet For CloudFoundry Bosh
Shell
10
star
31

remote-commands-servers

👪 Run remote ssh commands on multiple servers
Python
9
star
32

monitoring

Checks for various monitoring
Shell
9
star
33

chatops_slack

🚀 Python Slack ChatOps
Python
7
star
34

elasticsearch-cli-tool

🏪 CLI tools for ealsticsearch
Python
6
star
35

developer-technical-selling

💵 Do a better technical selling as a developer
5
star
36

linkedin-grow-influence

🔌 How To Improve Professional Influence In Linkedin
5
star
37

challenges-k8s-monitoring

Notes for deep dive into Kubernetes monitoring
5
star
38

cheatsheet-emacs-A4

📖 Emacs lisp cheatsheet
Emacs Lisp
5
star
39

challenges-aws-ecs

✍️ Case study using AWS ECS to setup personal wordpress
PHP
5
star
40

challenges-k8s-crd

Kubernets CRD: extend k8s resource
Dockerfile
4
star
41

cheatsheet-ruby-A4

📖 Advanced Ruby Syntax In A4
4
star
42

detect_suspicious_process

Detect suspicious process
Python
4
star
43

directory-cli-tool

📁 CLI tools for directories
Shell
3
star
44

python-hosts-tool

📍 Manage /etc/hosts in an organized way by Python
Python
3
star
45

code-with-docker

Use docker to write code in different languages
Shell
3
star
46

www.dennyzhang.com

Personal blog: DevOps, Cloud, Life
Shell
3
star
47

challenges-k8s-logging

Notes for deep dive into Kubernetes logging
3
star
48

challenges-k8s-storage

Notes for deep dive into Kubernetes storage
3
star
49

maintain-github-repos

👪 KnowledgeBase: Grow Influence From Maintaining Github Projects
3
star
50

maintain-it-blog

📚 Be a better IT Blogger
3
star
51

chef_community_cookbooks

🍖 Chef cookbooks for devops
Python
3
star
52

nmap-scan-docker

nmap network scan via docker
Python
3
star
53

shadowsocks-vpn-docker

🏗️ Docker shadowsocks VPN
Shell
2
star
54

dennytest

Github Repo to host various test scripts
Go
2
star
55

jenkins_image

💂‍♂️ Jenkins Docker Image
Shell
2
star
56

my-slides

Host my slides: devops, kubernetes, life, etc
2
star
57

cleanup_old_files

Clean old files in an organized way
Python
2
star
58

terraform_jenkins_digitalocean

Define Jenkins job to create and provision digitalocean VMs by terraform
Shell
2
star
59

python-aws-cli-wrapper

☁️ Wrapper layer of AWS CLI in Python
Python
2
star
60

cheatsheet-living-in-ca

👪 CheatSheet for living in Canifornia
2
star
61

quiz.dennyzhang.com

📖 Examine skills in a hard way
Shell
1
star
62

dennyzhang.github.io

dummy website
1
star
63

check_logfiles

nagios plugin to check log files
Perl
1
star
64

book-reading-cloud

📖 My book reading to be a good cloud engineer/architect
1
star
65

couchbase-cli-tool

Couchbase CLI Tools
Python
1
star
66

node_status_in_json

Query node status and return a structured json
Python
1
star
67

challenges-fluent-bit

Deep dive into fluent-bit
1
star
68

today-learning

Personal memo for #today-learnings in our DevOps slack group
1
star