20/5月

Leetcode

5385

  • 字符 replace
  • startwith
class Solution:
    def maxDiff(self, num: int) -> int:
        mx,mn=int(num),int(num)
        st=str(num)
        for i in range(10):
            for j in range(10):
                a,b=str(i),str(j)
                x=st.replace(a,b)
                if x.startswith('0'):
                    continue
                x=int(x)
                mx=max(mx,x)
                mn=min(mn,x)
        return mx-mn
  • zip 同时遍历两个相同len的数组
durations = [1, 7, 30]
costs = [2,7,15]

for c, d in zip(costs, durations):
    print(c,d)

缓存

@lru_cache(None)
  • 斐波那契数列
        f = [1, 1]
        while f[-1] < k:
            f.append(f[-1] + f[-2])
  • 新建2维数组
dp=[[0]*(2) for _ in range(3)]
  • 根据数组的第二位排序
s = [['g',2], ['e', 1], ['d', 4]]
s.sort(key = lambda x: x[1])

无需判断二维数组是否为空

        m = len(matrix)
        n = len(matrix) and len(matrix[0])
  • 向上取整
        from math import ceil
        size = min(ceil(m/2), ceil(n/2))

Java 连接字符串 StringBuilder O(n)时间

// "static void main" must be defined in a public class.
public class Main {
    public static void main(String[] args) {
        int n = 10000;
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < n; i++) {
            str.append("hello");
        }
        String s = str.toString();
    }
}
  • python 中if-else 可以用and 代替
left == right == 0 and res.append(s)
  • 阶乘
math.factorial(n)
  • python 拷贝
from copy import deepcopy

s = [[0, 0], [0, 0]]

s1 = s[:]
s2 = s.copy()
s3 = deepcopy(s)

s[0] = 1
s[1][0] = 5

s  : [1, [5, 0]]

s1 : [[0, 0], [5, 0]]
s2 : [[0, 0], [5, 0]]
s3 : [[0, 0], [0, 0]]
  • 英语文本预处理
def get_text():
    txt = open("1.txt", "r", encoding='UTF-8').read()
    txt = txt.lower()
    for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_‘{|}~':
        txt = txt.replace(ch, " ")      # 将文本中特殊字符替换为空格
    return txt
  • dict.get()
sum_dict[cur_sum] = sum_dict.get(cur_sum, 0) + 1

# 等于
if cur_sum in sum_dict:
    sum_dict[cur_sum] = sum_dict[cur_sum] + 1
else:
    sum_dict[cur_sum] = 0 + 1
  • 累积和遍历
import itertools
nums = [i for i in range(10)]
for s in itertools.accumulate(nums):
    print(s)

查看运行时间

my_arr = np.arange(1000000)

%time for _ in range(10): my_arr *= 2
  • 读取 .mat
import h5py
import numpy as np
import pandas as pd
import matplotlib.pyplot as plot

path = 'Brain_data1.mat'
mat = h5py.File(path)

mat.keys()

df = pd.DataFrame(mat["im_ori"])

s = np.array(df)
plot.imshow(s)
  • 两种正序倒序同时遍历
s = 'abccba'

for i in range(len(s)):
    print(s[i], s[~i])

for i, j in zip(s,s[::-1]):
    print(i, j)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值