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)
### 解析 Cron 表达式 '0 5/20 * * *' 的含义 Cron 表达式的格式由六个字段组成,分别表示秒、分、小时、日期、月份和星期。对于表达式 `0 5/20 * * *`,以下是其具体解析[^5]: - **第一个字段(秒):** 值为 `0`,表示任务将在每分钟的第 0 秒触发。 - **第二个字段(分钟):** 值为 `5/20`,表示从第 5 分钟开始,每隔 20 分钟执行一次任务。 - **第三个字段(小时):** 值为 `*`,表示每个小时都会触发任务。 - **第四个字段(日期):** 值为 `*`,表示每天都会触发任务。 - **第五个字段(月份):** 值为 `*`,表示每个月都会触发任务。 - **第六个字段(星期):** 值为 `*`,表示每周的每一天都会触发任务。 因此,Cron 表达式 `0 5/20 * * *` 的含义是从每天的每小时的第 5 分钟开始,每隔 20 分钟执行一次任务,且每次任务在第 0 秒触发[^1]。 ### 示例执行时间 假设当前时间为 `2023-10-01 08:00:00`,以下是该表达式的部分执行时间: - `2023-10-01 08:05:00` - `2023-10-01 08:25:00` - `2023-10-01 08:45:00` - `2023-10-01 09:05:00` - `2023-10-01 09:25:00` 以此类推,任务将按照上述规律持续执行。 ### 注意事项 如果任务启动时间不在指定的时间范围内,则第一次执行可能会延迟到下一个符合条件的时间点。例如,如果任务启动时间为 `08:07:00`,则第一次执行时间为 `08:25:00`,因为这是从第 5 分钟开始的第一个符合条件的时间点。 ```python from datetime import datetime, timedelta def calculate_next_cron_time(start_time): minute = start_time.minute hour = start_time.hour # 找到下一个符合条件的分钟数 if minute < 5: next_minute = 5 else: next_minute = ((minute - 5) // 20 + 1) * 20 + 5 if next_minute >= 60: next_minute -= 60 hour += 1 # 构造下一个时间点 next_time = start_time.replace(hour=hour, minute=next_minute, second=0, microsecond=0) if next_time <= start_time: next_time += timedelta(hours=1) return next_time # 示例启动时间 start_time = datetime(2023, 10, 1, 8, 7, 0) next_time = calculate_next_cron_time(start_time) print(next_time) ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值