使用Python刷题常用的模版代码集锦

阅读前看

以下常用的python代码模版是我在刷LeetCode时所作的笔记,若有误,还希望大家能够批评指正!

python3 中zip()函数

zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象,这样做的好处是节约了不少的内存。
我们可以使用 list() 转换来输出列表。
如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。

# paths是一个二维矩阵,transpose[1]表示paths[i][1],transpose[0]表示paths[i][0]
transpose = list(zip(*paths))

集合的差集运算

# 集合的差集运算 end和begin都是set
list(end - begin)

集合中去重操作

inter = set(nums1) & set(nums2)

默认字典collections.defaultdict()的使用

# collections.defaultdict(list)
import collections
 s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]

# defaultdict
collections.defaultdict(list)  d = 
  for k, v in s:
      d[k].append(v)
  print(d.items())
# 输出 dict_items([('yellow', [1, 3]), ('blue', [2, 4]), ('red', [1])])

# collections.defaultdict(set)
import collections
  s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
  d = collections.defaultdict(set)
  for k, v in s:
      d[k].add(v)
  print(d.items())
# 输出:dict_items([('yellow', {1, 3}), ('blue', {2, 4}), ('red', {1})])

# collections.defaultdict(int)
import collections
  s = 'mississippi'
  d = collections.defaultdict(int)
  for k in s:
      d[k] += 1
  print(d.items())
# 输出:dict_items([('m', 1), ('i', 4), ('s', 4), ('p', 2)])

python遍历键值对

for key,value in hashmap.items():
    print(key,value)

python遍历下标和值(字符串/数组)

for idx,val in enumerate(s):
    print(idx,val)

python二维列表展开成一维列表

# 二维数组展开成一维数组
_temp = [i for item in index_map.values() for i in item]

python删除指定元素

# 1.remove: 删除单个元素,删除首个符合条件的元素,按值删除
  str=[1,2,3,4,5,2,6]
  str.remove(2)
# 2.pop: 删除单个或多个元素,按位删除(根据索引删除)
  str=[0,1,2,3,4,5,6]
  str.pop(1) #pop删除时会返回被删除的元素
# 3.del:它是根据索引(元素所在位置)来删除
  str=[1,2,3,4,5,2,6]
  del str[1]

python字符串计数字符个数

S.count(i)  # S是字符串 i是字符

python数组计数数字个数

m = collections.Counter()
for num in nums1:
      m[num] += 1
c = Counter(nums1).most_common(k)  # 记录字典中出现频率前k的键值对,返回元组格式

python大小写转换(字符串)

# 小写转大写
str = "hELLO world!"
str = (str.upper())
# 大写转小写
str = "hELLO world!"
str = (str.lower())
# 首字母转大写,其余小写
str = "hELLO world!"
str = (str.capitalize())
# 每个单词首字母转大写,其余小写
str = "hELLO world!"
str = (str.title())

python all函数

# 元素除了是 0、空、None、False 外都算 True
# 全True返回True,否则返回False
if all(a < 0 for a in nums1) and (b > 0 for b in nums2)

python 使用字典替代map

# 标准写法,去避免key不能为list的情况
hash_map = dict()

python实现一个整数数组的前缀和(刷题很常用)

  s = [0 for i in range(len(A) + 1)]  # s代表前缀和,即s[i]表示sum(A[:i])
  for i in range(len(A)):
     s[i+1] = s[i] + A[i]

python检查字符串是否只由数字组成

c.isdigit()   # 是返回True,否则返回False

python实现一个字符串在另一个字符串出现次数的统计

count = collections.Counter(A.split()+B.split())
def check (s1,s2):  # s1,s2都是字符串
    return sum(map(lambda ch:s1.count(ch),s2))

python中字符和ASCII数字的相互转换

map(ord,t)  # 将字符串t中的字符映射为ASCII
chr(56)  # 将数字映射为相应的字符

python 根据字典的键值进行排序的方法

# 根据key排序
d = {'d1':2, 'd2':4, 'd4':1,'d3':3,}
for k in sorted(d):
  print(k,d[k])
# 根据value排序:__getitem__
for k in sorted(d,key=d.__getitem__):
  print(k,d[k])
# 反序:reverse=True
for k in sorted(d,key=d.__getitem__,reverse=True):
  print(k,d[k])
# 对dict_items进行排序
res = sorted(d.items(),key=lambda d:d[1],reverse=True)  # d[0]表示键,d[1]表示值
print(res)
# 区别
# items以列表形式返回字典键值对
# iteritems()以迭代器对象返回字典键值对

python字典查询(简便方法)

ab_map = dict()
for a in A:
    for b in B:
        ab_map[a + b] = ab_map.get(a + b, 0) + 1
# 哈希表,设预先置初始值为零
dicts = collections.defaultdict(int)

python实现整形数字的位数切分(很常用)

while num:
    rem = num % 10
    nums.append(rem)
    num //= 10
nums.reverse()

python快速创建数组

dp = [0] * (n + 1)

python按步幅遍历数组

for i in range(0,len(nums),2):
        print(i)

python.isalnum() 方法

# 检测字符串是否由字母和数字组成
s[L].isalnum()

python将字符串切分成单个的单词

print(list(strs))

python中进制转换(很常用)

# a是一个字符串"01010"
int(a,x) # 将x进制转十进制
bin(x) # 将x进制转二进制
oct(x) # 将二进制转八进制 
hex(x) # 将二进制转十六进制
# 八进制转十六进制可以借助十进制或者二进制为中间桥梁

python创建二维数组

 n, m = len(A), len(B)
 dp = [[0] * (m + 1) for _ in range(n + 1)]

python实现统计二维数组中的数

c = sum(bisect.bisect_right(row,mid) for row in matrix) 
# bisect.bisect_right(row,mid)计算row中元素值<=mid的数量(matrix是一个二维数组)

python判断括号的有效性(非常高频)

def isValid(x):
    stack = []
    for i in range(len(x)):
        if x[i] == '(':
            stack.append('(')
        elif stack!=[] and stack[-1] == '(':
            stack.pop()
        else:
            return False
    return stack==[]

python构建无向图/树

"""
:type edges: List[List[int]]
"""
connect = collections.defaultdict(list)
for i, (a, b) in enumerate(edges):
    connect[a].append(b)
    connect[b].append(a)

python中dict记住插入位置

from collections import OrderedDict
d = {'banana': 3, 'apple': 4}
od1 = OrderedDict({'banana': 3, 'apple': 4})
od2 = OrderedDict({'apple': 4, 'banana': 3})
print(od1 == od2)  # False
print(od1 == d)  # True

python实现排列组合(常用)

import itertools
排列:itertools.permutations(iterable)  #无重复,全排列
组合:itertools.combinations(iterable, r)
组合(包含自身重复):itertools.combinations_with_replacement(iterable, r)

python实现统计二进制中1的个数

# 计算二进制中1的个数
def count1(n):
    ans = 0
    while n != 0:
        n = n & (n - 1)
        ans += 1
    return ans
or
bins = [str(bin(i))[2:].count('1') for i in range(60)]

python实现字符串转换成数字

def changeToNums(self,s):
    nums = ""
    dict = {}
    count = 0
    for c in s:
        if(c in dict):
            continue
        else:
            dict[c] = str(count)
            count += 1
    for c in s:
        nums += dict[c]
    return nums

python实现列表升序排列

nums = sorted(nums, reverse = True)

python实现单链表中间节点查找(快慢指针,非常高频)

def findmid(head, tail):
    slow = head
    fast = head
    while fast != tail and fast.next!= tail :
        slow = slow.next
        fast = fast.next.next
    return slow

python 中心扩散法判别回文字符串(高频)

# s是字符串
def speard(l, r):
    count = 0
    while l >= 0 and r <= len(s)-1 and s[l] == s[r]:
        l -= 1
        r += 1
        count += 1
    return count

python实现计算全排列的个数(常用)

def mul(n):
    if n<=1:
        return 1
    else:
        return n*mul(n-1)

python库函数bisect模块

import bisect
 
L = [1,3,3,6,8,12,15]
x = 3
 
x_insert_point = bisect.bisect_left(L,x)  #在L中查找x,x存在时返回x左侧的位置,x不存在返回应该插入的位置..这是3存在于列表中,返回左侧位置1
print x_insert_point  # 1
 
x_insert_point = bisect.bisect_right(L,x)  #在L中查找x,x存在时返回x右侧的位置,x不存在返回应该插入的位置..这是3存在于列表中,返回右侧位置3
 
print x_insert_point  # 3
 
x_insort_left = bisect.insort_left(L,x)  #将x插入到列表L中,x存在时插入在左侧
print L  # [1, 3, 3, 3, 6, 8, 12, 15]
 
x_insort_rigth = bisect.insort_right(L,x) #将x插入到列表L中,x存在时插入在右侧    
 
print L  # [1, 3, 3, 3, 3, 6, 8, 12, 15]
  • 7
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值