在leetcode上刷题的笔记,记录了python和c++的常用操作
1. 异或运算可以实现两个数的交换、比较、加减运算等等。
异或的性质:任何数和0异或结果为他本身,任何数和本身异或结果为0:
0^a == a, a^a == 0, 而且异或满足交换律。
用异或交换两个数:
- void Swap(int& a,int& b){
- if(a!=b){
- a^=b;
- b^=a;
- a^=b;
- }
- }
2. python 内置函数 map()和reduce()。
【reduce()已经不再内置了,from functools import reduce】
map里有两个参数,一个函数一个迭代器,用法:把函数作用于迭代器内每个元素。例子:
>>>
def
f
(x):
...
return
x * x...
>>>
r = map(f, [
1
,
2
,
3
,
4
,
5
,
6
,
7
,
8
,
9
])
>>>
list(r)
[
1
,
4
,
9
,
16
,
25
,
36
,
49
,
64
,
81
]
reduce里的参数和map一样,但是其中的函数必须接受两个参数,reduce把结果继续和序列的下一个元素做累积计算。例子:
>>>
from
functools
import
reduce
>>>
def
add
(x, y):
...
return
x + y...
>>>
reduce(add, [
1
,
3
,
5
,
7
,
9
])
25
把map和reduce结合,写一个 str to int 函数:
DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} def str2int(s): def fn(x, y): return x * 10 + y def char2num(s): return DIGITS[s] return reduce(fn, map(char2num, s))
3. 创建一个计数字典
在一些对字符串或列表的操作里,需要创建一个记录字符串或列表中每个元素个数的字典,这里有几种方式:
s = "loveleetcode"
# 方法1
dic = {}
for i in s:
dic[i] = dic.get(i, 0)
dic[i] += 1
# 方法2
from collections import Counter
dic = Counter(s) # 自动创建,能够按数量降序排列
print(dic)