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)