知识点复习:
encoding = utf-8
import re
文件操作,读r:默认,写w, 追加a
with open (“d:\data\a.txt”, “r”, encoding=“utf-8”) as f: # “r” “utf-8” 有引号!
new_content = “”
# f.read() 读文件内容,返回字符串,太大的文件不能用这个方法
content = f.read()
# 正则替换
new_content = re.sub(r"\d+","",content)
写文件 w
with open (“d:\data\b.txt”, “w”, encoding=“utf-8”) as f:
f.write(new_content)
with open (“d:\data\b.txt”) as f:
print(f.read())
2、""“遍历目录下的所有文件,去掉字母以外字符”""
encoding=utf-8
import re
import os
def get_file_path_list(directory):
for root, dirs, files in os.walk(directory):
file_path_list = []
for each_file in files:
# 转成绝对路径!
file_path = os.path.join(root, each_file) # root
print(file_path)
file_path_list.append(file_path)
return file_path_list
def filter_file(file_path_list):
for file_path in file_path_list:
with open (file_path,“r”, encoding=“utf-8”) as f: # 语法
# 后两个参数写全,否则报错:UnicodeDecodeError: ‘gbk’ codec
# can’t decode byte 0xab in position 107: illegal multibyte sequence
new_content = re.sub(r"[^a-zA-Z]","", f.read())
with open (file_path, “w”, encoding=“utf-8”) as f:
f.write(new_content)
with open (file_path,“r”, encoding=“utf-8”) as f:
print(f.read())
if name==“main”:
directory = r"D:\data\目录练习"
file_path_list = get_file_path_list(directory)
filter_file(file_path_list)
找到列表中出现次数最多的字母
class Solution(object):
def commonChars(self, A):
“”"
:type A: List[str]
:rtype: List[str]
1、先转成一个大列表
2、遍历,生成dict, 找value 最大的
“”"
occur_times_d = {}
# 先转成一个大列表
A = list("".join(A))
# 遍历,生成dict, 找value 最大的
for letter in A:
if letter in occur_times_d:
occur_times_d[letter] += 1
else:
occur_times_d[letter] = 1
max_times_l = []
for k,v in occur_times_d.items(): # .items()
if v == max(occur_times_d.values()):
max_times_l.append(k)
return max_times_l
if name==“main”:
s = Solution()
print(s.commonChars([“bella”,“label”,“roller”]))
二分法
遍历查找:太慢,时间复杂度是n
算法:
pre:排好序的一个列表
分半查找
找到上、下边界、中值的索引:start、end、mid
while start < end 循环,
key 和 List(mid) 比较:
key 大, 则 start = mid + 1
key 小,则 start = mid - 1
key = ,则 start = mid,找到了
遍历结束,仍然没找到,则不存在
代码:
#encoding=utf-8
def binarySearch(List,key):
# 记录有序数组的上、下边界
start, end = 0, len(List)-1
while start <= end: # 有=号!
# 死循环,直到找到key
# 中位数
mid = (start + end)//2
if key == List[mid]:
# key 等于 mid,返回
return mid
elif key < List[mid]:
# key在mid右边的数组
end = mid - 1
elif key > List[mid]:
# key在mid左边的数组
start = mid + 1
return -1
if name==“main”:
List = [1, 6, 9, 15, 26, 38, 49, 57, 63, 77, 81, 93]
print(binarySearch(List, 15))
print(binarySearch(List, 16))
# 15在第3位
#不存在该数