Basic Pythonic tricks
- like char b = ‘a’ + 1; in python b = chr(ord(a)+1).
Lists
lis = [2,3,4,5,6,7]
lis = [1] + lis + [8]
# lis is now [1,2,3,4,5,6,7,8]
# flatten a grid
[x for row in grid for x in row]Sorting
lis = [2,3,4,5,6,7]
lis.sort() # returns nothing updates in-place
lis.sort(key=abs, reverse=True) # descending order of absolute val
sorted(lis, key=abs, reverse=True) # returns a copy leaves original as isSet
element you add must be hashable; for ex. list = [] is not hashable so we do set.add(tuple(list()))
myset = set()
myset.add(1)
myset.remove(2) # throws KeyError if 2 not present
myset.union(otherSet)
myset.intersection(otherSet)
myset.difference(otherSet)
myset.issubset(otherSet)
myset.issuperset(otherSet)Slicing
Often for string/array ops you may need to perform fancy iterations, tis always simpler to just be smart with slicing.
[start : stop : step]
for example, say you must reverse every k sized block for a list
lis = [1,2,3,4,5,6,7,8,9,10]
n = len(lis)
assert k > 0
for i in range(0,n,k):
lis[i:i+k] = lis[i:i+k][::-1]
# or just lis[i:i+k] = list(reversed(lis[i:i+k])) # reversed returns an iteratorWeb Things
Often, someone would want you to quickly spin up a web-dih project in smallest possible time. A wise man would choose fastapi for simplest syntax, less boilerplate circus and auto docs are of extreme importance when you debug you might not have do a hudred curls etc. You can always use express if you fancy that or maybe flask. But, I’ll strongly suggest sticking to fastapi
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def home():
return "hello"
@app.get("/users/{user_id}")
def get_user(user_id):
return {"user_id": user_id}
Now to run the simple server above.
# uvicorn <file name without py>:<name of fastapi object>
uvicorn server:app