蓝桥杯python知识总结(详细)

文章目录

  • python内置方法
  • python字符串方法
  • python模块
  • 动态规划
  • 回溯算法
  • 力扣简单题中所含知识点(前面数字为题号)
  • 力扣一些有意思的题目
  • python内置方法

    hex()  将数字转换为十六进制字符串
    oct()  将整数转换成八进制字符串               
    oct(int("39",16)) >>>'0o71'  十六进制转八进制
    chr(number)  返回数字对应的ascii码值
    divmod(a,b)  返回(a//b,a%b)
    

    python字符串方法

    s.swapcase() 将字符串中所有字母的大小写都反转
    s.upper() 将字符串所有的字母都转换为大写
    s.lower() 将字符串所有的字母都转换为小写
    s.isdigit() 检查字符串中的字符是否都是数字
    s.isnumeric() 检查字符串中的所有字符是否都是数字字符
    s.capitalize() 返回字符串的副本,但将第一个字符大写
    s.isalpha() 检查字符串中的所有字符是否都是字母
    s.isalnum() 检查字符串中的字符是否都是字母或数
    s.isspace() 检查字符串中的字符是否都是空白字符
    

    python模块

    statistics模块

    1、statistics.mean()  求算术平均值
    2、statistics.median() 计算数据的中位数,如果有两个中位数,则返回其平均值
       statistics.median_low() 数据中的低中位数
       statistics.median_high() 数据中的高中位数
    3、statistics.mode()  计算众数
    4、statistics.pvariance() 计算数据的总体方差
    

    collections模块

    1、collections.deque([])
            q = collections.deque([1, 2, 3, 4])
            q.rotate(1)
            print(q)  # [4, 1, 2, 3]
            q.rotate(1)
            print(q)  # [3, 4, 1, 2]
    2、collections.Counter()
        >>> import collections
        >>> collections.Counter([1,2,3,1,2,3,1,2])
        Counter({1: 3, 2: 3, 3: 2})
    

    datetime模块

    1、日期增加
    >>> import datetime
    >>> bt = datetime.date(2000,11,6)
    >>> print(bt)
    2000-11-06
    >>> a = datetime.timedelta(days=100)
    >>> a
    datetime.timedelta(days=100) #weeks / hours
    >>> b = a + bt
    >>> b
    datetime.date(2001, 2, 14)
    

    2、给定日期求星期

    bt.weekday():返回weekday,如果是星期一,返回0;如果是星期2,返回1,以此类推;
    bt.isoweekday():返回weekday,如果是星期一,返回1;如果是星期2,返回2,以此类推;
    

    3、标准化

    >>> bt.isoformat()
    '2000-11-06'
    

    4、返回公元公历开始到现在的天数

    >>> bt.toordinal()
    730430
    

    5、输出

    >>> bt.__format__('%Y/%m/%d')
    '2000/11/06'
    

    calendar模块

        1、判断是否为闰年
        >>> import calendar
        >>> calendar.isleap(2022)
        False
    
       2、返回两年之间的闰年总数
        >>> calendar.leapdays(2000,2020)
    

    动态规划

    大致解法

    1、定义数组元素的含义,清楚dp[i]的含义,表示的结果
    2、找出数组元素之间的关系式,即动态转移方程,递推公式
    3、找出初始值,例如第一个元素值

    回溯算法

    框架

    ans = []
    def trace(path,choices):
        if len(path) == len(nums):
            ans.append(list(path))
    
        for i in choices:
            if i in path:       
                continue
            path.append(i)
            trace(path,choices)
            path.pop()      
        return ans
    nums = [1,2,3]
    print(trace([],nums))
    >>> [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
    
    res = []  
    path = []  
    def bt(nums,startIndex):
        res.append(path[:])
        for i in range(startIndex,len(nums)):
            path.append(nums[i])
            bt(nums,i+1)
            path.pop()
    nums = [1,2,3]
    bt(nums,0)
    print(res)
    >>> [[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]
    

    #9 字符串、列表反转

    s = "123456"
    s[::-1]
    >>>"654321"
    

    回溯算法例题 # 17 39 40 46 47 77 78 90 1079

    力扣简单题中所含知识点(前面数字为题号)

    #14 enumerate() 函数

    用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
     max()和min(),字符串是可以比较的,按照ascII值排 abb, aba,abac,最大为abb,最小为aba
    

    zip函数

    a = [1,2,3]  b = [4,5,6]
    list(zip(a,b))
    >>>[(1,4),(2,5),(3,6)]
    strs = ["flower","flow","flight"] 
    list(zip(*strs))
    

    #17 #46 #47 itertools模块

    import itertools
       1)product
    for i in itertools.product('ab', 'cd'):
        print(i)
    >>>('a', 'c')
       ('a', 'd')
       ('b', 'c')
       ('b', 'd')
    
      2)permutations
        list(itertools.permutations('ABC'))
        >>>[('A', 'B', 'C'), ('A', 'C', 'B'), ('B', 'A', 'C'), ('B', 'C', 'A'), ('C', 'A', 'B'), ('C', 'B', 'A')]
        list(itertools.permutations('ABC', 2))
        >>>[('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B')]
    
        3)combinations
        list(itertools.combinations("ABC",2))
        >>>[('A', 'B'), ('A', 'C'), ('B', 'C')]
    
        4)accumulate 可指定函数,默认为求和
        list(itertools.accumulate([0,1,0,1,1,2,3,5]))
        >>>[0, 1, 1, 2, 3, 5, 8, 13]
        list(itertools.accumulate([0,1,0,1,1,2,3,5],max))
        >>>[0, 1, 1, 1, 1, 2, 3, 5]
    

    #20 寻找元素时,可以考虑替换字符串元素
    .replace(“()”,“”)

    #27 删除某一元素时,可以while ture 用remove
    remove删除列表第一个为指定值的元素

    #28 find在字符串中查找子串,如果找到,返回字串的第一个字符的索引,找不到返回-1
    a = “asdfghjkl” b = “jkl”
    KMP算法

    #49 字母异位词分组
    字典的用法

    strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
    res = []
    dic = {}
    for s in strs:
        keys = "".join(sorted(s))
        if keys not in dic:
            dic[keys] = [s]
        else:
            dic[keys].append(s)
    print(list(dic.values()))
    >>>[['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]
    

    #50 幂函数

    .pow(a,b)
    

    #58 按照指定字符将字符串拆分成序列 s.split(" ")
    将字符串开头和末尾的空白删除,返回删除后的结果 s.strip()

    #64 创建二维列表方法

    dp = [[0 for _ in range(n)] for j in range(m)]
    dp = [[0] * n for i in range(m)]
    

    #67 二进制转十进制 int(“二进制字符串”,2)
    十进制转二进制 bin(整数)[2:]

    #88 删除列表最后一个元素

    list.pop()
    

    #136 只出现一次的数字用异或运算

    a = 0
    for i in nums:
        a = a^i
    

    #191 二进制
    bin() 返回一个整数 int 或者长整数 long int 的二进制表示。

    #231 2的幂次方的二进制数,只有一位为一

    #268 进行数组加减或者删除重复的元素
    set() 函数创建一个无序不重复元素集,可进行关系测试,删除重复数据

    #367 不用库求完全平方数

    1、完全平方数是前n个连续奇数的和 1+3+5+7+9+…+(2n-1)=n^2
    2、n ** 0.5 % 1
    

    #500 set函数可以进行比较

    a = set('qwertyuiop')
    b = set("reagdagd")
    return b<a
    

    #520 string.islower() #检查字符串中的所有字母都是小写的
    string.isupper() #检查字符串中的所有字母都是大写的
    string.istitle() 检查字符串中位于非字母后面的字母都是大写的,且其他所有字母都是小写的/可以检测字符串首字母是否为大写

    #599 字典的键值对反过来

    b = {v:k for k,v in d.items()}
    寻找键
    for i in d:
        if ans[i] == a:
            l.append(i)
    

    #605 考虑边界问题时,可在数组前后各加入一个数

    #645 找连续数组中不同元素时,可以用求和找

    #709 字符串所有的字母都转换为小写
    s.lower()

    #914 求数组中所有数的公因数

     while len(ans) != 1:
            ans = sorted(ans)
            c = math.gcd(ans[0],ans[1])
            if c == 1:
                print("1")
            else:
                ans.append(c)
                ans.remove(ans[0])
                ans.remove(ans[0])
        print(ans[0])
    

    #922 将两个列表交叉合并

    from itertools import chain
    list(chain.from_iterable(zip(a, ans)))
    
    [i for n in zip(a, ans) for i in n]
    

    #1154 日期确定是当年的第几天

    time.strptime(date, "%Y-%m-%d")[-2]
    

    #1185 日期确定星期

    datetime.datetime(year,month,day).strftime("%w")
    

    #1207 求数组中所有元素出现的个数

    from collections import Counter
    arr = [1,2,2,1,1,3]
    print(Counter(arr).values())
    >>>dict_values([3, 2, 1])
    
    from collections import Counter
    arr = [1,2,2,1,1,3]
    print(Counter(arr))
    >>>Counter({1: 3, 2: 2, 3: 1})
    

    #1232 直线斜率不要用除法,除数可能为0,转用乘法
    y2 / y1 == x2 / x1
    x1 * y2 == x2 * y1

    #1304 列表生成器

    [i for i in range(1,n)]
    

    #1323 replace将指定字符串替换为另一个字符串
    str.replace(指定字符,目标字符,不超过的次数)

    #1331 可以利用enumerate创建字典后,根据元素找下标

    a = sorted(set(arr))
    d = {}
    for i, v in enumerate(a, 1):
        d[v] = i
    

    #1337 字典根据值的大小进行排序

    d = sorted(d.items(), key=lambda item:item[1])
    

    #1342 不知道循环次数时用while

    #1346 判断列表是否为空
    len() 注意特殊的0,二倍还是为0

    #1365 找比指定的数小或者大的数 ,可以先进行排序,再通过索引的值获得有多少个这种数

    #1380 矩阵中的幸运数
    获取二维数组每列元素

    matrix = [[3,7,8],[9,11,13],[15,16,17]]
    colmin = [i for i in zip(*matrix)]
    >>>[(3, 9, 15), (7, 11, 16), (8, 13, 17)]
    

    #1556 千位分隔符

    print({:,}.format(n).replace(",","."))
    n = 123456
    >>>123.456
    

    #1608 bisect.bisect_left(list , i) 查找该数值将会插入的位置并返回

    #1624 字符串.rfind() 查找字符最后一次出现的位置,没有则返回-1

    #1710 按照某种规律进行排序

    l = [[5,10],[2,5],[4,7],[3,9]]
    l = sorted(l, key=lambda x:-x[1])
    >>>[[5, 10], [3, 9], [4, 7], [2, 5]]
    
    l = ["adss","a","sad","sd"]
    l = sorted(l,key=lambda x:len(x))
    >>>['a', 'sd', 'sad', 'adss']
    

    #1863 找出给定列表的所有子集

    l = [[]]
    for x in nums:
        l.extend([i + [x] for i in l])
    

    对序列中的元素进行累计 eg:求所有元素的异或总和

    from functools import reduce
    j = [1,2,3,4,5]
    reduce(lambda x,y:x ^ y,j)
    

    #1880 返回单个字母的特定值,可以先返回其Unicode码

      ord("a")
      >>>97
    

    #1979 求a和b最大公约数

      gcd(a,b)
    

    #5947 返回一个新集合,该集合的元素既包含在集合 x 又包含在集合 y 中

      x.intersection(y)
    

    力扣一些有意思的题目

    偏数学归纳题:#6 z字形变换 #441 排列硬币 #1518 换酒问题
    #258 各位相加 https://leetcode-cn.com/problems/add-digits/
    思路惊奇:#645 错误的集合 https://leetcode-cn.com/problems/set-mismatch/
    #461 汉明距离 https://leetcode-cn.com/problems/hamming-distance/(异或运算)
    #246 中心对称数 https://leetcode-cn.com/problems/strobogrammatic-number/
    #838 推多米诺 https://leetcode-cn.com/problems/push-dominoes/ (元素替换)
    #453 最小操作次数使数组元素相等 https://leetcode-cn.com/problems/minimum-moves-to-equal-array-elements/
    #1002 查找共用字符 https://leetcode-cn.com/problems/find-common-characters/
    #657 机器人能否返回原点 https://leetcode-cn.com/problems/robot-return-to-origin/
    #2124 检查是否所有 A 都在 B 之前 https://leetcode-cn.com/problems/check-if-all-as-appears-before-all-bs/
    #908 最小差值 I https://leetcode-cn.com/problems/smallest-range-i/
    #343 整数拆分 https://leetcode-cn.com/problems/integer-break/

    lambda表达式用法:#1287 #1122 #1710 #1337

    记住最直接的思路:
    #5957 向字符串添加空格 https://leetcode-cn.com/problems/adding-spaces-to-a-string/
    #1935 可以输入的最大单词数 https://leetcode-cn.com/problems/maximum-number-of-words-you-can-type/
    #283 移动零 https://leetcode-cn.com/problems/move-zeroes/
    #169 多数元素 https://leetcode-cn.com/problems/majority-element/
    #459 重复的子字符串 https://leetcode-cn.com/problems/repeated-substring-pattern/
    #2006 差的绝对值为 K 的数对数目 https://leetcode-cn.com/problems/count-number-of-pairs-with-absolute-difference-k/

    物联沃分享整理
    物联沃-IOTWORD物联网 » 蓝桥杯python知识总结(详细)

    发表回复