python中高效刷题的扩展包

作者: 玖月晴 | 来源:发表于2019-06-01 22:22 被阅读1次

更多精彩内容,请关注【力扣简单题】

计数器

如果我们想统计列表或字符串中每个元素出现的次数,我们可以这样做:

def counter(l):
    count_dict = {}
    for e in l:
        if e in count_dict.keys():
            count_dict[e] += 1
        else:
            count_dict[e] = 1
    return count_dict

s = "apple"
c = counter(s)
print(c)
# {'a': 1, 'p': 2, 'l': 1, 'e': 1}

如果我们使用collection模块中的Counter,就可以快速进行统计:

from collections import Counter
s = "apple"
c = Counter(s)
print(c)
# Counter({'p': 2, 'a': 1, 'l': 1, 'e': 1})

列表也是可以统计的。

生成的Counter类可以看做一个字典,相当于字典的继承,支持加减操作,例如:

l1 = [7, 7, 7, 7, 8, 8, 8]
l2 = [7, 7, 7, 8, 8, 8, 8, 9]
c1, c2 = Counter(l1), Counter(l2)
print(c1+c2)
# Counter({7: 7, 8: 7, 9: 1})
print(c1-c2)
# Counter({7: 1})

排列组合

一个箱子里有写着1, 2, 3, 4的四张卡片,从中任意抽两张:

  1. 不考虑先后顺序,求所有可能的组合,需要使用combinations;

  2. 考虑先后顺序,且无放回的抽取,需要使用permutations;

  3. 考虑先后顺序,且有放回的抽取,需要使用product;

实验效果:

 from itertools import product, combinations, permutations
nums = [1, 2, 3, 4]
c = combinations(nums, r=2)
a = permutations(nums, r=2)
p = product(nums, repeat=2)
print(list(c))
# [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
print(list(a))
# [(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)]
print(list(p))
# [(1, 1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (2, 3), (2, 4), (3, 1), (3, 2), (3, 3), (3, 4), (4, 1), (4, 2), (4, 3), (4, 4)]

数学计算

有时候,我们需要用到数学计算包,例如计算平方,对数等情况,数学计算包可以大大提高我们的编程效率。

from math import log, sqrt, pow
print(log(16, 2))
# 4
print(sqrt(2))
# 1.4142135623730951
print(pow(2, 6))
# 64.0

灵活使用上述扩展包,会使我们的编码变得高效。

如有疑问或建议,欢迎评论区留言~

相关文章

网友评论

    本文标题:python中高效刷题的扩展包

    本文链接:https://www.haomeiwen.com/subject/plrztctx.html