Python学习系列零碎tips

Python整型、浮点型最大值

import sys
sys.maxsize
float("inf")

# 922,3372,0368,5477,5807
# inf

Python counter

import collections

a = ['i', 'like', 'i', 'hate']
print(collections.Counter(a))

# Counter({'i': 2, 'like': 1, 'hate': 1})

Python reduce & list相加

# reduce
from functools import reduce
import operator

def func(x, y):
    return x + y

a = [[1, 2, 3], [4, 5], [6]]
b = [1, 2, 3, 4, 5]
print(reduce(func, a))
print(reduce(operator.add, b, 2))

# list相加
print([1, 2, 3] + [4, 5, 6])

# [1, 2, 3, 4, 5, 6]
# 17
# [1, 2, 3, 4, 5, 6]

Python enumerate

a = [[1, 2, 3], [4, 5], [6]]
for i, v in enumerate(a):
    print(i, v)

# 0 [1, 2, 3],注意这里index从0开始
# 1 [4, 5]
# 2 [6]

Python 运算符优先级 & 负数整除

print(2 << 1 + 1)
print(-5//10)

# 8,先算1+1,然后2左移两位,8
# -1,画出函数图像即可

Python 数组索引 & iter

a = [1, 2, 3]
print(a[2:2])
for i in iter(a):
    print(i)

# [],注意这里不包含a[2]
# 1
# 2
# 3

Python __init____new__

class A(object):

    def __init__(self, num=None):
        print('This is the __init__: ', id(self))
        print('init', num)

    def __new__(cls, *args, **kwargs):
        print('This is the __new__: ', id(cls))
        return object.__new__(cls)

a = A()

# This is the __new__:  1686957167432
# This is the __init__:  1686964512416
# init None

Python快速幂

import datetime


def pow_normal(x, y):
    if y < 0:
        if x == 0:
            print("Zero can not be denominator!")
            return
        else:
            x = 1. / x
            y = -y
    res = 1
    while y > 0:
        res *= x
        y -= 1
    return res


def pow_quick(x, y):
    if y < 0:
        if x == 0:
            print("Zero can not be denominator!")
            return
        else:
            x = 1. / x
            y = -y
    res = 1
    while y > 0:
        if y & 1:  # 若y为奇数,则先乘1个x,使y变为偶数
            res *= x
        x *= x
        y //= 2
    return res


def pow_quick_mod(x, y, base):
    if y < 0:
        if x == 0:
            print("Zero can not be denominator!")
            return
        else:
            x = 1. / x
            y = -y
    res = 1
    while y > 0:
        if y & 1:
            res *= x
            res %= base
        x *= x % base
        x %= base
        y //= 2
    return res


st = datetime.datetime.now()
for i in range(50):
    pow_normal(99, 99999)
et = datetime.datetime.now()
print(et - st)
st = et
for i in range(50):
    pow_quick(99, 99999)
et = datetime.datetime.now()
print(et - st)
st = et
for i in range(50):
    pow_quick_mod(99, 99999, 10 ** 9 + 7)
et = datetime.datetime.now()
print(et - st)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值