Tuesday, 14 September 2021

Python cheat sheet

String


# loop through
for c in "abc":
	print(c)

# string replace with return the end result. It does not change original result
date = datePart.replace("th", "")

# string split to list. X will be [welcome, to, jungle]
txt = "welcome to jungle"
x = txt.split()

# substring. will print 20
datePart = "20th"
print(datePart[0:2])

#substring to the end. will print 0th
datePart = "20th"
print(datePart[1:])

# generate an array for all lower case letters (a...z)
letters = list(string.ascii_lowercase)

#convert a decimal integer to binary string. get "111"
s1 = bin(7).replace("0b", "")

#zero left fill. The length is the length of the result string
s= "123"
# get "00123"
s=s.zfill(5)

#The count() method returns the number of times a specified value appears in the string.
print ("foobar".count("o")) # print 2

# get a char's ascii value. 'a' is 97. For code below, will return 98
print(ord('b'))

#ascii value to char. here print 'a'
print(chr(97))

#find and rfind. return 0 and 4
"abcda".find("a")
"abcda".rfind("a")

# str to int. get 9 for the code below
int("09")

hash


#create hash
hash1 = {}

#initiate hash with default data. use get to set a default value. will print out 0
print (hash1.get('a', 0))

#assigin value
hash1['a'] = 10

# access hash. print out 10
count = hash1['a']
print(count)

# check if key exist in hash. should get false
if 'c' not in hash1:
    print ("not have")
        
# loop through
for k in hash1:
    print(hash1[k])

# clear or empty a hash
hash1.clear()

# get hash keys
hash1.keys()

#decouple with hash
keys = list(pointHash.keys())

array

# append. arr becomes 1,2,4
arr = [1,2]
arr.append(4)

# create two dimension array
		dp = []
        for i in range(n):
            dp.append([10000]*n)

# find index of a element
nums = [2,3,49,1]

try:
	i = nums.index(49)
except ValueError:
	pass
#length
print(len(nums))

# join array into string
" ".join(nums)

# sort. This is in house sort
nums.sort()

# sort two dimention array by x[0], then x[1]
intervals.sort(key=lambda x:[x[0], x[1]])

# sort by x[0]
stockPrices.sort(key=lambda x:x[0])

# reverse in house sort
inventory.sort(reverse=True)

# pop at index
nums.pop(0)

# remove from the begin
nums.pop(0)

# remove from the end
nums.pop()

#initial array with 0
ans = [0] * 100

# initiate array with 0 (another way). The below will get [0,0,0,0,0]
arr=[]
arr = [0 for i in range(5)]

#reverse range
reversed(range(100))

#initialize two dimension array
dp = [[0 for x in range(m)] for y in range(m)] 

# list comprehension
 starts = [a for a, b in flowers]
 ends = [b for a, b in flowers]

Set

# create a empty set
s = set()

# add an element to set
s.add(1)

# check length of set
print(len(s))

# check contains
if 2 in s:

Binary search built in functions

bisect.bisect_left(a, x, lo=0, hi=len(a)) : Returns leftmost insertion
point of x in a sorted list. Last two parameters are optional, 
they are used to search in sublist.

bisect.bisect_right(a, x, lo=0, hi=len(a)) Returns rightmost insertion 
point of x in a sorted list a. Last two parameters are optional,
they are used to search in sublist.

index = bisect_right(arr, val)

Permutation

for p in permutations([1,2,3], 3): 
	print (p)
#output
(1, 2, 3)
(1, 3, 2)
(2, 1, 3)
(2, 3, 1)
(3, 1, 2)
(3, 2, 1)

Rest API

Send a post

import requests
import json

url = 'http://localhost:5000'
myobj = {'somekey': 'somevalue'}
headers = {'content-type':'application/json'}

x = requests.post(url, data =json.dumps( myobj), headers=headers)

print(x.text)

Math

#integer div.It will return 4
9//2

# find gcd of two integers
gcd = math.gcd(d, price)

# val is 8
val = max(3, 8)

#power. mod is optional. But if need mod, use it. It is 
#much faster than ans=pow(x,y) ans = ans%mod
pow(x, y, mod)
ans = ans + pow(2, r-i, 1000000007)

Inner Function


def countDaysTogether(self, arriveAlice: str, leaveAlice: str, arriveBob: str, leaveBob: str) -> int:
    months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    def getDayOfYear(dayStr:str)->int:
        arrMonth = int(dayStr[0:2])
        arrDay = int(dayStr[3:5])

Hard questions

1799. Maximize Score After N Operations

class Solution:
    myMap = {}
    def maxScore(self, nums: List[int]) -> int:
        def getM(k, nums):
            # build cache key
            cacheK = ' '.join(str(x) for x in nums)+ "k:" + str(k)
            if cacheK in self.myMap:
                return self.myMap[cacheK]

            if len(nums)==2:
                ans = k*math.gcd(nums[0], nums[1])
                self.myMap[cacheK] = ans
                return ans
            
            ans =0
            l = len(nums)
            for i in range(l-1):
                for j in range(i+1, l):
                    n1 = k*math.gcd(nums[i], nums[j])
                    left = []
                    for h in range(l):
                        if h!=i and h!=j:
                            left.append(nums[h])
                    n2 = getM(k+1, left)

                    if (n1+n2) > ans:
                        ans = n1 + n2
            self.myMap[cacheK] = ans
            return ans

        nums.sort()
        return getM(1, nums)

heap

#Leetcode 2542
class Solution:
    def maxScore(self, nums1: List[int], nums2: List[int], k: int) -> int:
        l = len(nums1)
        nums = []
        for i in range(l):
            nums.append([nums1[i], nums2[i]])
        
        #sort by the second element
        nums.sort(key=lambda x:x[1])
        nums.reverse()

        ans, curSum = 0, 0

        myHeap = []
        for i in range(k):
            curSum += nums[i][0]
            heapq.heappush(myHeap, nums[i][0])
        ans = curSum * nums[k-1][1]

        for i in range(k, l):
            out = heapq.heappop(myHeap)
            curSum = curSum-out + nums[i][0]
            heapq.heappush(myHeap, nums[i][0])
            ans = max(ans, curSum * nums[i][1])

        return ans
#Leetcode 1464
import heapq
class Solution:
    def maxProduct(self, nums: List[int]) -> int:
        for i in range(len(nums)):
            nums[i] = nums[i]*-1
        
        heapq.heapify(nums)
        # return smallest
        a = heapq.heappop(nums)
        b = heapq.heappop(nums)
       
        return (a*-1 -1) * (b*-1-1)

Run codes

#Leetcode 1992
from typing import List
class Solution:
    def findFarmland(self, land: List[List[int]]) -> List[List[int]]:
        def getFarm(f: List[int], a:int, b:int):
            
            if a<f[0] or b<f[1]:
                f[0]=a
                f[1]=b
            if a>f[2] or b>f[3]:
                f[2] = a
                f[3] = b
            return f
            
        rows = len(land)
        cols = len(land[0])

        ones = []

        # find all ones
        for i in range(rows):
            for j in range(cols):
                if land[i][j] == 1:
                    ones.append([i, j])
        
        #put ans
        ans = []
        for one in ones:
            #some one has been grouped
            if land[one[0]][one[1]] != 1:
                continue
            
            # one itself is a farmland
            x, y = one[0], one[1]
            queue = [[x,y]]
            myLand = [x, y, x, y]

            while len(queue)>0:
                size = len(queue)
                for i in range(size):
                    point = queue.pop(0)
                    a, b = point[0], point[1]

                    #left
                    if b!=0 and land[a][b-1] == 1:
                        myLand = getFarm(myLand, a, b-1)
                        land[a][b-1] = 0
                        queue.append([a, b-1])

                    #right
                    if b!=cols-1 and land[a][b+1] == 1:
                        myLand = getFarm(myLand, a, b+1)
                        land[a][b+1] = 0
                        queue.append([a, b+1])

                    #up
                    if a!=0 and land[a-1][b]==1:
                        myLand = getFarm(myLand, a-1, b)
                        land[a-1][b] = 0
                        queue.append([a-1, b])

                    #down
                    if a!=rows-1 and land[a+1][b]==1:
                        myLand = getFarm(myLand, a+1, b)
                        land[a+1][b] = 0
                        queue.append([a+1, b])
            ans.append(myLand)
        
        return ans
        
obj = Solution()
land = [[1,0,0],[0,1,1],[0,1,1]]
res = obj.findFarmland(land)
print(res)

django

commands

django-admin startproject project-name

python manage.py startapp app-name

python manage.py runserver

# open a shell to run some db query
python manage.py shell

Handle Form

# get post data
post_id = request.POST.get("post_id")

Use env variables

# create .env file in the project directory
api_key=mysecfretetemmsmsm

# in settings.py
from dotenv import load_dotenv
load_dotenv()

# to access env variable
import os
os.getenv("api_key")

var dump

from pprint import pprint
pprint(request.POST)

Versions

#find version
python -V
pip -V
python3.7 -m pip list

#show version used to store library
pip show openai

Install Python OpenAi Module

python3.7 -m pip install --upgrade pip
python3.7 -m pip install openai

No comments:

Post a Comment