├── .gitignore ├── 01_基础分章节 ├── 01_basic │ ├── 01~05.py │ └── 06~10.py ├── 02_seq │ ├── Heap.py │ ├── Queue.py │ ├── ex1.py │ ├── ex2.py │ ├── ex3.py │ ├── ex4.py │ ├── ex_01列表生成式.py │ ├── ex_02切片.py │ ├── ex_03字典.py │ ├── ex_04列表切片排序.py │ └── set_random.py ├── 03_loopif │ ├── ex1.py │ ├── ex2.py │ ├── ex3.py │ ├── ex4.py │ ├── ex5_permutations.py │ └── ex6.py ├── 04_str_re │ ├── 4.1字符串.py │ ├── test1.py │ ├── test2.py │ ├── 查找一个匹配项.py │ └── 查找多个匹配项.py ├── 05_function │ ├── 05_KochDrawV1.py │ ├── 05_hanoi.py │ └── 06_1.py ├── 06_OOP │ ├── Array.py │ ├── dictTree.py │ ├── ex1_Student.py │ └── ex2_vector.py ├── 07_FILE │ ├── 2.txt │ ├── Open&Close.py │ ├── binfile.py │ ├── chardet_test.py │ ├── demo1.py │ ├── demo1_new.py │ ├── demo2_pickle.py │ ├── demo3_visitdir.py │ ├── document_1.txt │ ├── document_3.txt │ ├── encodedecode.py │ ├── files │ │ ├── 1.txt │ │ ├── GBK.txt │ │ └── read.txt │ ├── integers.txt │ ├── list │ ├── pickle.dat │ ├── test.bin │ ├── write.py │ ├── 习题1.txt │ ├── 习题1_大小写转换.py │ ├── 习题2_二进制文件读写.py │ ├── 习题2_成绩字典.bin │ ├── 习题3_文件移动.py │ ├── 习题5_修改工作目录.py │ └── 习题6_判断目录中是否存在文件.py └── 08_Exception │ ├── 3.4_Exception_1.py │ ├── 3.4_Exception_2.py │ ├── 3.4_Exception_3.py │ ├── 3.4_Exception_4.py │ ├── 3.4_note.md │ └── 3.x_file.py ├── 02_MOOC习题 ├── 02_0贪心思考题.py ├── 02_1判断正负.py ├── 02_2判断奇偶.py ├── 02_3判断日期合法.py ├── 02_4计算邮费.py ├── 03_0求n的平方根.py ├── 03_1datetime.py ├── 03_2谁是罪犯.py ├── 03_3穷举法.py ├── 03_4作业1.py ├── 03_5作业2.py ├── 04_0统计字符串.py ├── 04_1列表与复杂排序思考题.py ├── 04_2二分查找.py ├── 04_3二分查找思考题.py ├── 04_4自除数.py ├── 04_5排序.py ├── 04_6作业3.py ├── 04_7作业4.py ├── 05_1哥德巴赫.py ├── 05_2进制.py ├── 05_3圆周率.py ├── 05_4Base64.py ├── 05_5递归.py ├── 05_6回文.py ├── 05_作业.py ├── 05_作业2.py ├── 05_汽车钥匙模拟题.py ├── 06_作业 │ ├── ResultInts.txt │ ├── Sort.txt │ ├── StrInts.txt │ ├── cat1.txt │ ├── cat2.txt │ └── numbers.txt ├── 06_作业2_提取整数.py ├── 06_作业3_数字分析.py ├── 06_作业_内容粘贴.py ├── 07_作业1_PM2.5.py └── 09_期末考试.py ├── 03_本科编程题 ├── 01_2016_ETC.py ├── 01_2016_ETC_datetime.py ├── 02_2016_字符串信息.py ├── 03_2017_文本统计.py ├── 04_2017_数字统计.py ├── 05_2018年.py ├── 06_2019年.py ├── Files │ ├── 01_data.txt │ ├── 01_report.txt │ ├── 02_string.txt │ ├── 03_data.txt │ ├── 03_result.txt │ ├── 03_result1.txt │ ├── 04_result.txt │ └── ch7_Folder │ │ ├── file1.txt │ │ ├── file2.txt │ │ ├── file3.txt │ │ ├── file4.txt │ │ └── merge.txt ├── ch2_484950.py ├── ch2_51menber.py ├── ch7_54copy.py ├── ch7_55sort.py ├── ch7_56merge.py ├── ch7_57_word.py ├── ch7_58Names.py ├── ch7_59_largefile.py └── 题目 │ ├── 01_2016年期末.pdf │ ├── 02_2016年期中.pdf │ ├── 03_2017年1.pdf │ ├── 04_2017年2.pdf │ ├── 05_2018年.pdf │ ├── 06_2019年.pdf │ └── Python编程习题集chxx.pdf ├── 04_历年复试真题 ├── 2005_真题素数和.py ├── 2016_词频统计.py ├── 2017_二进制数据文件.py ├── 2018_.py ├── 2020_判等差数列存在性.py ├── 2021_四道编程题 │ ├── 2021_四道题目.txt │ ├── 26239 _1.py │ ├── 26239_2.py │ ├── 26239_3.py │ └── 26239_4.py ├── Data │ ├── 01_data.txt │ ├── 03_data.txt │ ├── 03_result │ ├── 03_result.txt │ ├── 2016_input.txt │ ├── 2016_output.txt │ ├── 2017_data.bin │ ├── 2018_data.bin │ ├── ch7_54_copy.txt │ ├── ch7_54_new.txt │ ├── ch7_55_Numbers.txt │ ├── ch7_55_Sort.txt │ ├── ch7_57_newword.txt │ ├── ch7_57_word.txt │ ├── ch7_58_Names.txt │ └── ch7_58_new_word.txt ├── 复试真题C语言实现.md └── 复试真题Python实现.md ├── 05_leetcode ├── 1.两数之和.py ├── 1002.查找常用字符.py ├── 1013.!将数组分成和相等的三个部分.py ├── 1025.除数博弈.py ├── 104.二叉树的最大深度.py ├── 1046.最后一块石头的重量.py ├── 11.!!双指针_盛水最多的容器.py ├── 116.填充每个节点的下一个右侧节点指针.py ├── 118.!杨辉三角.py ├── 1184.公交站间的距离.py ├── 125.验证回文串.py ├── 1252.奇数值单元格的数目.py ├── 1276.!!方程_不浪费原料的汉堡制作方案.py ├── 1281.整数各位积和之差.py ├── 1287.超过25%的元素.py ├── 13.罗马数字转整数.py ├── 1323.6和9组成的最大数.py ├── 1329.将矩阵按对角线排序.py ├── 1337.战斗力最弱的K行.py ├── 14.!最长公共前缀.py ├── 141.环形链表.py ├── 142.环形链表II.py ├── 167.两数之和-ii-输入有序数组.py ├── 168.Excel表列名称.py ├── 171.Excel表列序号.py ├── 178.Bigram.py ├── 189.旋转数组.py ├── 19.删除链表的倒数第-n-个结点.py ├── 198.打家劫舍.py ├── 20.有效的括号.py ├── 200.BFSDFS_岛屿数量.py ├── 209.长度最小的子数组.py ├── 21.合并两个有序链表.py ├── 215.数组中的第k个最大元素.py ├── 226.翻转二叉树.py ├── 26.删除排序数组中的重复项.py ├── 263.丑数.py ├── 27.移除元素.py ├── 278.第一个错误的版本.py ├── 28.实现strStr().py ├── 283.移动零.py ├── 287.!!寻找重复数.py ├── 29.!!两数相除.py ├── 290.单词规律.py ├── 295.数据流的中位数.py ├── 3.无重复字符的最长子串.py ├── 326.3的幂.py ├── 344.反转字符串.py ├── 35.搜索插入位置.py ├── 355.设计推特.py ├── 367.有效的完全平方数.py ├── 409.最长回文串.py ├── 445.!!两数相加II.py ├── 46.!!全排列.py ├── 461.汉明距离.py ├── 466.未完成!!!统计重复个数.py ├── 474.一和零.py ├── 476.数字的补数.py ├── 485.最大连续1的个数.py ├── 5.最长回文子串.py ├── 50.leetcode.py ├── 509.斐波那契数.py ├── 520.检测大写字母.py ├── 521.最长特殊序列I.py ├── 53.最大子序和.py ├── 541.反转字符串II.py ├── 542.!!01矩阵.py ├── 55.!!贪心_跳跃游戏.py ├── 557.反转字符串中的单词-iii.py ├── 560.!!前缀和_和为K的子数组.py ├── 561.数组拆分I.py ├── 567.字符串的排列.py ├── 572.另一个树的子树.py ├── 575.分糖果.py ├── 617.合并二叉树.py ├── 628.三个数的最大乘积.py ├── 64.最小路径和.py ├── 645.错误的集合.py ├── 657.机器人能否返回原点.py ├── 680.!验证回文字符串II.py ├── 69.x的平方根.py ├── 695.岛屿的最大面积.py ├── 7.!位_整数反转.py ├── 70.爬楼梯.py ├── 704.二分查找.py ├── 733.图像渲染.py ├── 748.!re,counter最短完整词.py ├── 771.宝石与石头.py ├── 804.摩尔斯密码词.py ├── 811.子域名访问计数.py ├── 819.最常见的词.py ├── 821.字符的最短距离.py ├── 824.山羊拉丁文.py ├── 832.翻转图像.py ├── 844.!生成器_比较含退格的字符串.py ├── 860.柠檬水找零.py ├── 876.链表的中间结点.py ├── 883.三维形体投影面积.py ├── 888.公平的糖果交换.py ├── 9.回文数.py ├── 905.按奇偶排序数组.py ├── 908.最小差值I.py ├── 914.卡牌分组.py ├── 922.按奇偶排序数组II.py ├── 925.长按键入.py ├── 929.独特的电子邮件.py ├── 937.重新排列日志文件.py ├── 94.二叉树的中序遍历.py ├── 941.有效的山脉数组.py ├── 953.!验证外星语词典.py ├── 961.重复N次的元素.py ├── 970.强整数.py ├── 973.最接近远点的K个点.py ├── 977.有序数组的平方.py ├── 98.验证二叉搜索树.py ├── 983.!!动态规划_最低票价.py ├── 989.数组形式的整数加法.py ├── JZOF.03.数组中重复的数字.py ├── JZOF.36.二叉搜索树与双向链表.py ├── JZOF.38.字符串的排列.py ├── JZOF.44.数字序列中某一位的数字.py ├── JZOF.48.最长不含重复字符的子字符串.py ├── M01.01_判断字符是否唯一.py ├── M01.04_回文排列.py ├── M17_打印1到最大的n位数.py ├── M51_!!!未完成_数组中的逆序对.py ├── Offer 56.I 数组中数字出现的次数.py ├── Offer 56.II 数组中数字出现的次数.py ├── Offer 59 - II. 队列的最大值.py ├── Offer 62_圆圈中最后剩下的数字.py └── about-leetcode.md ├── 06_其他 ├── FFT 大数乘法 │ ├── FFT_multiply.py │ └── FFT_multiply2.py ├── Huawei │ ├── 01字符串最后一个单词长度.py │ ├── 02计算字符个数.py │ └── 03明明的随机数.py ├── PTA │ ├── 1001_3n+1.py │ ├── 1002_要通过.py │ ├── 1005_继续3n+1.py │ ├── 1007_素数对猜想.py │ ├── 1009_说反话.py │ ├── 1011_A+BandC.py │ ├── 1013_数素数.py │ ├── 1015_德才论.py │ ├── 1017_A除以B.py │ ├── 1019_数字黑洞.py │ ├── 1021_个位数统计.py │ ├── 1023_组个最小数.py │ ├── 1025_反转链表.py │ └── 1027_打印沙漏.py ├── Similarity.py ├── feibo.py ├── standard library_queue.ipynb ├── 剑指offer │ └── 牛牛找工作.py ├── 原地删除重复.py ├── 简易程序 │ ├── Typora │ │ └── TyporaPiture.py │ ├── recoder.py │ ├── temp.py │ ├── 力扣题重命名.py │ └── 统计代码行数.py └── 算法 │ ├── change_making.py │ ├── fractional_backpack.py │ └── permutation.py └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | .idea 3 | .vscode 4 | -------------------------------------------------------------------------------- /01_基础分章节/01_basic/01~05.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | def func1(): 4 | a, b = eval(input("input a,b:")) 5 | res = divmod(a, b) 6 | print('{0[0]}, {0[1]}'.format(res)) 7 | 8 | def func2(): 9 | name = input("input your name:") 10 | print(len(name)) 11 | 12 | def func3(): 13 | pi = 3.14 14 | h, r = eval(input()) 15 | v = h * pi * r ** 2 16 | d, m = divmod(20, v) 17 | if m : 18 | print('{}'.format(int(d+1))) 19 | else: 20 | print(d) 21 | 22 | def func4(): 23 | x1,y1 = eval(input("x1,y1")) 24 | x2,y2 = eval(input("x2,y2")) 25 | dis = ((x1-x2)**2 + (y1-y2)**2)**0.5 26 | print(dis) 27 | 28 | def func5(): 29 | import random 30 | num = random.randint(100,999) 31 | print(num) 32 | s = str(num) 33 | s2 = ''.join(reversed(s)) 34 | print(s2) 35 | 36 | if __name__ == "__main__": 37 | # func1() 38 | # func2() 39 | # func3() 40 | # func4() 41 | func5() 42 | pass -------------------------------------------------------------------------------- /01_基础分章节/01_basic/06~10.py: -------------------------------------------------------------------------------- 1 | def func6(): 2 | num = int(input('输入一个三位数整数:')) 3 | sum = 0 4 | while num != 0: 5 | num, mod = divmod(num, 10) 6 | sum += mod 7 | print(sum) 8 | 9 | def func7(): 10 | x1,y1,x2,y2,x3,y3 = eval(input("x1,y1,x2,y2,x3,y3:")) 11 | def dis(x1,y1,x2,y2): 12 | return ((x1-x2)**2+(y1-y2)**2)**0.5 13 | 14 | side1 = dis(x1,y1,x2,y2) 15 | side2 = dis(x1,y1,x3,y3) 16 | side3 = dis(x3,y3,x2,y2) 17 | s = sum((side1,side2,side3))/2 18 | area = (s*(s-side1)*(s-side2)*(s-side3))**0.5 19 | print(area) 20 | 21 | if __name__ == "__main__": 22 | # func6() 23 | func7() 24 | pass -------------------------------------------------------------------------------- /01_基础分章节/02_seq/Heap.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | import random 3 | 4 | data = list(range(10)) 5 | random.shuffle(data) 6 | 7 | # 建堆 8 | heap = [] # 使用heapq包对列表进行操作 9 | for n in data: 10 | heapq.heappush(heap, n) # 数据入堆 11 | 12 | # 弹出堆的最小元素(堆会自动重建) 13 | heapq.heappop(heap) 14 | 15 | # 列表转换为堆 16 | myheap = [i for i in range(10)] 17 | heapq.heapify(myheap) 18 | 19 | # heapreplace(heap, item) -> value. Pop and return the current smallest value, and add the new item. 20 | heapq.heapreplace(myheap, 6) 21 | 22 | heapq.nlargest(3, myheap) # 返回前3个最大的元素 23 | heapq.nsmallest(3, myheap) # 返回前3个最小的元素 24 | -------------------------------------------------------------------------------- /01_基础分章节/02_seq/Queue.py: -------------------------------------------------------------------------------- 1 | import queue 2 | 3 | # FIFO 4 | q = queue.Queue() 5 | q.put(0) 6 | q.put(1) 7 | print(q.queue) 8 | print(q.get()) # 出队 9 | 10 | # LIFO 11 | LIFOQueue = queue.LifoQueue(3) # 可以选择设置队列大小 12 | 13 | # 优先级队列PriorityQueue 14 | # Variant of Queue that retrieves open entries in priority order (lowest first). 15 | # Entries are typically tuples of the form: (priority number, data). -------------------------------------------------------------------------------- /01_基础分章节/02_seq/ex1.py: -------------------------------------------------------------------------------- 1 | import random as rd 2 | 3 | 4 | def countbyset(): 5 | # 使用集合 6 | l = [rd.randint(0, 100) for i in range(1000)] 7 | x = set(l) 8 | for i in x: 9 | print(i, l.count(i)) 10 | 11 | 12 | def countbydict(): 13 | # 使用字典 14 | l = [rd.randint(0,100) for i in range(1000)] 15 | d = {} 16 | for i in l: 17 | d[i] = d.get(i, 0) + 1 18 | 19 | for k,v in d.items(): 20 | print(k, v, sep=':') 21 | 22 | 23 | if __name__ == '__main__': 24 | # countbyset() 25 | countbydict() -------------------------------------------------------------------------------- /01_基础分章节/02_seq/ex2.py: -------------------------------------------------------------------------------- 1 | 2 | l = eval(input('请输入一个列表e.g. [1,2,3,4,5]')) 3 | start, end = eval(input('input front and rear list 2,4')) 4 | 5 | print(l[start:end+1]) # 切片含头不含尾 -------------------------------------------------------------------------------- /01_基础分章节/02_seq/ex3.py: -------------------------------------------------------------------------------- 1 | 2 | d = {'a': 1, 'b': 2} 3 | while True: 4 | k = input('请输入键') 5 | if k == '': 6 | break 7 | else: 8 | print(d.get(k, '您输入的键不存在')) 9 | -------------------------------------------------------------------------------- /01_基础分章节/02_seq/ex4.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | l = [random.randint(0, 100) for i in range(20)] 4 | print(l) 5 | l2 = sorted(l[:10]) + sorted(l[10:], reverse=True) 6 | print(l2 7 | ) -------------------------------------------------------------------------------- /01_基础分章节/02_seq/ex_01列表生成式.py: -------------------------------------------------------------------------------- 1 | """ 2 | 编写程序,生成包含1000个0~100之间的随机整数,并统计每个元素的出现次数。 3 | """ 4 | 5 | import random 6 | num_list = [random.randint(0,100) for _ in range(1000)] 7 | fre_dict = dict.fromkeys(range(0,101), 0) 8 | for num in num_list: 9 | fre_dict[num] += 1 10 | print(fre_dict) -------------------------------------------------------------------------------- /01_基础分章节/02_seq/ex_02切片.py: -------------------------------------------------------------------------------- 1 | """ 2 | 用户输入一个列表和2个整数作为下标 3 | 然后输出列表中介于2个下标之间的元素组成的子列表 4 | 5 | """ 6 | 7 | num_list = eval(input("输入[1,2,3,4,5]形式的列表:")) 8 | start, end = map(int, input("输入空格分开的两个整数:").split()) 9 | print(num_list[start:end+1]) -------------------------------------------------------------------------------- /01_基础分章节/02_seq/ex_03字典.py: -------------------------------------------------------------------------------- 1 | """ 2 | 字典 用户输入键 输出值 3 | 若键不存在,则输出您输入的键不存在 4 | """ 5 | 6 | dict1 = {} 7 | 8 | if __name__ == "__main__": 9 | while True: 10 | try: 11 | key = input("请输入键:") 12 | if key in dict1: 13 | print("值为", dict1[key]) 14 | else: 15 | value = input("您输入的键不存在,请输入该键要对应的值:") 16 | dict1[key] = value 17 | except: 18 | break -------------------------------------------------------------------------------- /01_基础分章节/02_seq/ex_04列表切片排序.py: -------------------------------------------------------------------------------- 1 | """ 2 | 生成20个随机数的列表,然后将前10个元素升序排列,后10个降序排列 3 | """ 4 | 5 | import random 6 | 7 | num_list = [random.randint(0,100) for _ in range(20)] 8 | print(num_list) 9 | num_list[0:10] = sorted(num_list[0:10]) 10 | num_list[10:20] = sorted(num_list[10:20], reverse=True) 11 | print(num_list) -------------------------------------------------------------------------------- /01_基础分章节/02_seq/set_random.py: -------------------------------------------------------------------------------- 1 | import random 2 | import time 3 | 4 | 5 | def generate_random1(start, end, num): 6 | l = [] 7 | while True: 8 | element = random.randint(start, end) 9 | if element not in l: 10 | l.append(element) 11 | if len(l) == num: 12 | break 13 | return l 14 | 15 | 16 | def generate_random2(start, end, num): 17 | s = set() 18 | while True: 19 | s.add(random.randint(start,end)) 20 | if len(s) == num: 21 | break 22 | return s 23 | 24 | 25 | if __name__ == '__main__': 26 | start = time.time() 27 | for i in range(10000): 28 | l = generate_random2(1, 100, 50) 29 | print('time used:', time.time() - start) 30 | -------------------------------------------------------------------------------- /01_基础分章节/03_loopif/ex1.py: -------------------------------------------------------------------------------- 1 | """ 2 | 运行用户输入4位整数作为年份,判断其是否为闰年。 3 | 被400整除是,能被4整除却不能被100整除是 4 | """ 5 | 6 | 7 | def judge(year): 8 | if year%4 == 0: 9 | if year % 100==0 and year % 400!=0: 10 | return False 11 | else: 12 | return True 13 | else: 14 | return False 15 | 16 | if __name__ == "__main__": 17 | year = int(input("请输入一个年份:")) 18 | print(judge(year)) 19 | -------------------------------------------------------------------------------- /01_基础分章节/03_loopif/ex2.py: -------------------------------------------------------------------------------- 1 | """ 2 | 生成一个包含50个随机整数的列表,删除其中的奇数 3 | """ 4 | import random 5 | num_list = [random.randint(0,100) for _ in range(50)] 6 | print(num_list) 7 | 8 | for i in range(len(num_list))[::-1]: 9 | if num_list[i] % 2 != 0: 10 | del num_list[i] 11 | 12 | print(num_list) -------------------------------------------------------------------------------- /01_基础分章节/03_loopif/ex3.py: -------------------------------------------------------------------------------- 1 | """ 2 | 生成一个包含20个随机整数的列表, 3 | 然后对其偶数下标的元素进行降序排序, 4 | 奇数下标的元素位置不变。 5 | """ 6 | 7 | import random 8 | num_list = [random.randint(0,100) for _ in range(20)] 9 | print(num_list) 10 | print("偶数下标", num_list[::2]) 11 | num_list[::2] = sorted(num_list[::2], reverse=True) 12 | print(num_list) 13 | print("偶数下标", num_list[::2]) 14 | -------------------------------------------------------------------------------- /01_基础分章节/03_loopif/ex4.py: -------------------------------------------------------------------------------- 1 | """ 2 | 用户输入小于1000的整数 3 | 对其进行因式分解 4 | """ 5 | 6 | x = int(input("输入小于1000的整数")) 7 | temp = x 8 | i = 2 9 | result = [] 10 | while True: 11 | if temp == 1: 12 | break 13 | if temp%i == 0: 14 | result.append(i) 15 | temp = temp//i 16 | else: 17 | i += 1 18 | print(x, '=', '*'.join(map(str, result))) 19 | -------------------------------------------------------------------------------- /01_基础分章节/03_loopif/ex5_permutations.py: -------------------------------------------------------------------------------- 1 | """ 2 | 输出所有由 1 2 3 4四个数字组成的素数 3 | 并且在每个素数中每个数字只使用一次 4 | """ 5 | import itertools as it 6 | import sympy 7 | 8 | for seq in it.permutations(range(1,5),4): 9 | num = int(''.join(map(str,seq))) 10 | if sympy.isprime(num): 11 | print(num) -------------------------------------------------------------------------------- /01_基础分章节/03_loopif/ex6.py: -------------------------------------------------------------------------------- 1 | """ 2 | x<0 0 3 | 0<=x<5 x 4 | 5<=x<10 3x-5 5 | 10<=x<20 0.5x-2 6 | 20<=x 0 7 | """ 8 | 9 | def divfunc(x): 10 | if x < 10: 11 | if x>=5: 12 | return 3*x-5 13 | elif x>=0: 14 | return x 15 | else: 16 | # x<0 17 | return 0 18 | elif x < 20: 19 | return 0.5*x -2 20 | else: 21 | # 20<=2 22 | return 0 -------------------------------------------------------------------------------- /01_基础分章节/04_str_re/test1.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | # 匹配长度5~20的字符串,以字母开头能带下划线和句点 第二个字符必须是. 4 | pattern1 = '^[a-zA-Z]{1}\.([a-zA-Z0-9._]){4,18}$' 5 | r1 = re.compile(pattern1) 6 | 7 | pattern2 = r'^[a-zA-Z]{1}\.([a-zA-Z0-9._]){4,18}$' 8 | r2 = re.compile(pattern2) 9 | 10 | while True: 11 | try: 12 | st = input("input a string ") 13 | if r1.match(st): 14 | print("r1 match") 15 | else: 16 | print("r1 dismatch") 17 | if r2.match(st): 18 | print("r2 match") 19 | else: 20 | print("r2 dismatch") 21 | except: 22 | break -------------------------------------------------------------------------------- /01_基础分章节/04_str_re/test2.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | # pattern1 = '(.)\\1+' 4 | pattern1 = r'(.)\1+' 5 | 6 | r1 = re.compile(pattern1) 7 | 8 | 9 | while True: 10 | try: 11 | st = input("input a string ") 12 | if r1.match(st): 13 | print("r1 match") 14 | else: 15 | print("r1 dismatch") 16 | 17 | except: 18 | break -------------------------------------------------------------------------------- /01_基础分章节/04_str_re/查找一个匹配项.py: -------------------------------------------------------------------------------- 1 | """ 2 | search: 查找任意位置的匹配项 3 | match: 从字符串开头匹配 4 | fullmatch: 整个字符串与正则完全匹配 5 | """ 6 | -------------------------------------------------------------------------------- /01_基础分章节/04_str_re/查找多个匹配项.py: -------------------------------------------------------------------------------- 1 | """ 2 | findall 3 | finditer 4 | """ 5 | 6 | import re 7 | 8 | 9 | text = "草莓君 草莓君" 10 | pattern = r"草莓君" 11 | 12 | print(a:=re.findall(pattern, text), type(a[0])) # List[str] 13 | 14 | 15 | for obj in re.finditer(pattern, text): 16 | print(type(obj), obj.group()) # 草莓君 -------------------------------------------------------------------------------- /01_基础分章节/05_function/05_KochDrawV1.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | def koch(size,n): 3 | if n ==0: 4 | turtle.fd(size) 5 | else: 6 | for angle in [0,60,-120,60]: 7 | turtle.left(angle) 8 | koch(size/3,n-1) 9 | 10 | def main(): 11 | turtle.setup(600,600) 12 | turtle.penup() 13 | turtle.goto(-200,100) 14 | turtle.pendown() 15 | turtle.pensize(2) 16 | level = 2 17 | koch(400,level) 18 | turtle.right(120) 19 | koch(400,level) 20 | turtle.right(120) 21 | koch(400,level) 22 | turtle.hideturtle() 23 | main() -------------------------------------------------------------------------------- /01_基础分章节/05_function/05_hanoi.py: -------------------------------------------------------------------------------- 1 | # hanoi 2 | 3 | count = 0 4 | def hanoi(n,src,dst,mid): 5 | global count 6 | if n == 1 : 7 | print("{}:{}->{}".format(1,src,dst)) 8 | count += 1 9 | else : 10 | hanoi(n-1,src,mid,dst) 11 | print("{}:{}->{}".format(n,src,dst)) 12 | count += 1 13 | hanoi(n-1,mid,dst,src) 14 | 15 | hanoi(5,'A','B','C') -------------------------------------------------------------------------------- /01_基础分章节/05_function/06_1.py: -------------------------------------------------------------------------------- 1 | 2 | A = {'A','B',"CDE",1,5,2} 3 | try: 4 | while True: 5 | print(A.pop(),end="") 6 | except: 7 | pass -------------------------------------------------------------------------------- /01_基础分章节/06_OOP/ex2_vector.py: -------------------------------------------------------------------------------- 1 | """ 2 | 设计一个三维向量,并实现向量的加法、减法以及向量与标量的乘法和除法运算 3 | 运算符重载 4 | """ 5 | import random 6 | 7 | class Vector3: 8 | def __init__(self, shape=(1,1,1)): 9 | if isinstance(shape, tuple) and len(shape) == 3: 10 | self.shape = shape 11 | self.creatMat() 12 | else: 13 | print('must be a tuple of 3 integer.') 14 | return 15 | 16 | def creatMat(self): 17 | mat = [[] for _ in range(self.shape[0])] 18 | for i in range(self.shape[0]): 19 | mat[i] = [[] for _ in range(self.shape[1])] 20 | for j in range(self.shape[1]): 21 | mat[i][j] = [random.randint(0,100) for _ in range(self.shape[2])] 22 | self.mat = mat 23 | 24 | def setValue(self, i, j, k, v): 25 | self.mat[i][j][k] = v 26 | 27 | def __str__(self): 28 | return str(self.mat) 29 | 30 | def __add__(self, v2): 31 | if self.shape != v2.shape: 32 | print('not in the same shape') 33 | return None 34 | else: 35 | v3 = Vector3(shape=self.shape) 36 | for i in range(self.shape[0]): 37 | for j in range(self.shape[1]): 38 | for k in range(self.shape[2]): 39 | v3.setValue(i,j,k, self.mat[i][j][k]+v2.mat[i][j][k]) 40 | return v3 41 | 42 | if __name__ == "__main__": 43 | V1 = Vector3((2,2,2)) 44 | V2 = Vector3((2,2,2)) 45 | print(V1, V2) 46 | V3 = V1 + V2 47 | print(V3) -------------------------------------------------------------------------------- /01_基础分章节/07_FILE/2.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Zaaachary/Python-Foundation-Suda/05d7adabeceff41ce9639c729d2c8b78f4f05467/01_基础分章节/07_FILE/2.txt -------------------------------------------------------------------------------- /01_基础分章节/07_FILE/Open&Close.py: -------------------------------------------------------------------------------- 1 | # 一个用来测试文件及目录操作的程序 2 | 3 | # 文件的开启和关闭 4 | fileObj = open("document_1.txt", 'r+') 5 | words = fileObj.readline() 6 | print(words, end="") 7 | fileObj.close() 8 | 9 | # 用 with 语句来自动调用 close() 方法 10 | with open("document_1.txt", 'r+') as f: 11 | print("file \"document_1.txt\" has been opened! Sent by with open() as ") 12 | 13 | 14 | # 避免文件打开异常 15 | try: # 捕获异常法 16 | fileObj = open("document_2.txt", "r") 17 | except FileNotFoundError: 18 | print('file "document_2.txt" not exisit! Sent by try except ') 19 | 20 | import os # os模块判断文件是否存在 21 | if not os.path.exists("document_2.txt"): 22 | print('file "document_2.txt" not exisit! Sent by os\n') 23 | 24 | # 读文件的相关函数 25 | fileObj = open("document_1.txt", 'r+') 26 | words = fileObj.readline() # 读取一行存到words 27 | print(words,end="") 28 | 29 | # words = fileObj.read(4) # 读取N个字符 30 | # print(words,end="") 31 | 32 | line_list = fileObj.readlines() # 读取所有行并存到列表中 33 | for L in line_list: 34 | print(L,end="") 35 | fileObj.close() 36 | 37 | # 利用for循环获取文件中的每一行 38 | # for line in input(): 39 | # print(line,end="") #input 内输入的内容看做序列 40 | for line in open("document_1.txt","r"): 41 | print(line,end="") 42 | 43 | # 写文件相关函数 44 | # output.write(str) 45 | # output.writelines(seq) 46 | output = open("document_3.txt", "w+") 47 | output.write("'document_3.txt' has been writen\n") 48 | output.writelines(line_list) -------------------------------------------------------------------------------- /01_基础分章节/07_FILE/binfile.py: -------------------------------------------------------------------------------- 1 | f = open('test.bin', 'wb+') 2 | 3 | f.write(b'12,34,53,25,61,28,78/n') 4 | 5 | str1 = '中文/n测试/n' 6 | bytes1 = bytes(str1, encoding='gbk') 7 | f.write(bytes1) 8 | 9 | f.seek(0) 10 | bytes2 = f.read() 11 | str2 = bytes2.decode('gbk', 'ignore') 12 | print(str2) 13 | 14 | f.close() 15 | 16 | -------------------------------------------------------------------------------- /01_基础分章节/07_FILE/chardet_test.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /01_基础分章节/07_FILE/demo1.py: -------------------------------------------------------------------------------- 1 | if __name__ == '__main__': 2 | # 读取数据 3 | filename = 'demo1.py' 4 | with open(filename, 'r', encoding='utf-8') as fp: 5 | lines = fp.readlines() 6 | # 调整数据 7 | 8 | # 未对齐 9 | data1 = [] 10 | i = 1 11 | for line in lines: 12 | data1.append(line.rstrip() + ' # ' + str(i) + '\n') 13 | i += 1 14 | 15 | # 对齐方式1 str.ljust + rstrip() 16 | data2 = [] 17 | max_len = max([len(line) for line in lines]) 18 | i = 1 19 | for line in lines: 20 | data2.append('{0}{1}\n'.format(line.rstrip().ljust(max_len, ' ') + '# ', str(i))) 21 | i += 1 22 | # 对齐方式2 23 | data3 = [line.rstrip()+' '*(100-len(line))+'#'+str(index)+'\n' for index,line in enumerate(lines)] 24 | 25 | # 写入文件 26 | fp = open(filename[:-3] + '_new.py', 'a+') 27 | # 使用writelines 28 | fp.writelines(data2) 29 | # 使用print输入到文件中 30 | for line in data3: 31 | print(line, file=fp, end='') 32 | fp.close() 33 | -------------------------------------------------------------------------------- /01_基础分章节/07_FILE/demo2_pickle.py: -------------------------------------------------------------------------------- 1 | import pickle 2 | 3 | 4 | def pdump(): 5 | global f 6 | n = 4 7 | i = 1300 8 | a = 99.2 9 | dic = {'1': 'a', '2': 'b'} 10 | try: 11 | pickle.dump(n, f) 12 | pickle.dump(i, f) 13 | pickle.dump(a, f) 14 | pickle.dump(dic, f) 15 | except Exception as e: 16 | print(e) 17 | finally: 18 | f.flush() 19 | 20 | 21 | def pload(): 22 | global f 23 | f.seek(0) 24 | n = pickle.load(f) 25 | i = 1 26 | while i < n: 27 | x = pickle.load(f) 28 | print(x) 29 | i = i + 1 30 | 31 | 32 | if __name__ == '__main__': 33 | global f 34 | f = open('pickle.dat', 'wb+') 35 | pdump() 36 | pload() 37 | f.close() 38 | 39 | -------------------------------------------------------------------------------- /01_基础分章节/07_FILE/demo3_visitdir.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | 4 | def visit_dir(path): 5 | if not os.path.isdir(path): 6 | print("Errpr:", path, "is not a directory or doesn t exisit.") 7 | else: 8 | for l in os.listdir(path): 9 | sub_path = os.path.join(path, l) 10 | print(sub_path) 11 | if os.path.isdir(sub_path): 12 | visit_dir(sub_path) 13 | 14 | 15 | def visit_dir2(path): 16 | if not os.path.isdir(path): 17 | print("Errpr:", path, "is not a directory or doesn t exisit.") 18 | else: 19 | # 使用walk方法 20 | list_dirs = os.walk(path) 21 | for root, dirs, files in list_dirs: 22 | for d in dirs: 23 | # 列出root下的所有目录 24 | print(os.path.join(root, d)) 25 | for f in files: 26 | # 列出root下的所有文件 27 | print(os.path.join(root, f)) 28 | 29 | 30 | if __name__ == '__main__': 31 | path = input("input path: ") 32 | # visit_dir1(path) 33 | visit_dir2(path) 34 | -------------------------------------------------------------------------------- /01_基础分章节/07_FILE/document_1.txt: -------------------------------------------------------------------------------- 1 | file "document_1.txt" has been opened! 2 | this is second line of "document_1.txt" . 3 | word 4 | line 4 5 | line 5 6 | line 6 -------------------------------------------------------------------------------- /01_基础分章节/07_FILE/document_3.txt: -------------------------------------------------------------------------------- 1 | 'document_3.txt' has been writen 2 | this is second line of "document_1.txt" . 3 | word 4 | line 4 5 | line 5 6 | line 6 -------------------------------------------------------------------------------- /01_基础分章节/07_FILE/encodedecode.py: -------------------------------------------------------------------------------- 1 | with open('GBK.txt', 'rb') as f: 2 | b1 = f.read() 3 | print("GBK bytes:", b1) 4 | s1 = b1.decode('GBK') 5 | print("GBK text:", s1) 6 | b2 = s1.encode('utf-8') 7 | print("\nutf-8 bytes:", b2) 8 | s2 = b2.decode('utf-8') 9 | print("utf-8 text:", s2) -------------------------------------------------------------------------------- /01_基础分章节/07_FILE/files/1.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Zaaachary/Python-Foundation-Suda/05d7adabeceff41ce9639c729d2c8b78f4f05467/01_基础分章节/07_FILE/files/1.txt -------------------------------------------------------------------------------- /01_基础分章节/07_FILE/files/GBK.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Zaaachary/Python-Foundation-Suda/05d7adabeceff41ce9639c729d2c8b78f4f05467/01_基础分章节/07_FILE/files/GBK.txt -------------------------------------------------------------------------------- /01_基础分章节/07_FILE/files/read.txt: -------------------------------------------------------------------------------- 1 | abc你好呀 -------------------------------------------------------------------------------- /01_基础分章节/07_FILE/list: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Zaaachary/Python-Foundation-Suda/05d7adabeceff41ce9639c729d2c8b78f4f05467/01_基础分章节/07_FILE/list -------------------------------------------------------------------------------- /01_基础分章节/07_FILE/pickle.dat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Zaaachary/Python-Foundation-Suda/05d7adabeceff41ce9639c729d2c8b78f4f05467/01_基础分章节/07_FILE/pickle.dat -------------------------------------------------------------------------------- /01_基础分章节/07_FILE/test.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Zaaachary/Python-Foundation-Suda/05d7adabeceff41ce9639c729d2c8b78f4f05467/01_基础分章节/07_FILE/test.bin -------------------------------------------------------------------------------- /01_基础分章节/07_FILE/write.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | 4 | 5 | def main(): 6 | f = open('integers.txt','w') 7 | for count in range(500): 8 | number = random.randint(1,500) 9 | f.write(str(number) + "\n") 10 | f.close() 11 | 12 | def readfile(): 13 | f = open('integers.txt','r') 14 | sum = 0 15 | for line in f: 16 | line = line.strip() 17 | number = int(line) 18 | sum += number 19 | print("The sum is %d" % (sum)) 20 | f.close() 21 | 22 | 23 | 24 | if __name__ == "__main__": 25 | main() 26 | readfile() -------------------------------------------------------------------------------- /01_基础分章节/07_FILE/习题1.txt: -------------------------------------------------------------------------------- 1 | HELLO WORLD! 2 | NICE TO BE HERE. -------------------------------------------------------------------------------- /01_基础分章节/07_FILE/习题1_大小写转换.py: -------------------------------------------------------------------------------- 1 | """ 2 | 英文文本文件,读取内容将大写小写转换。 3 | """ 4 | 5 | def readwords(filename): 6 | f = open(filename, 'r') 7 | lines = f.readlines() 8 | print('已读取' + filename) 9 | return lines 10 | 11 | def switch(lines): 12 | for index, line in enumerate(lines): 13 | lines[index] = ''.join([ch.lower() if ch.isupper() else ch.upper() for ch in line]) 14 | print('已转换大小写') 15 | return lines 16 | 17 | def writewords(filename, lines): 18 | f = open(filename, 'w') 19 | for line in lines: 20 | f.write(line) 21 | print('已写入' + filename) 22 | f.close() 23 | 24 | if __name__ == "__main__": 25 | filename = './习题1.txt' 26 | writewords(filename, switch(readwords(filename))) 27 | -------------------------------------------------------------------------------- /01_基础分章节/07_FILE/习题2_二进制文件读写.py: -------------------------------------------------------------------------------- 1 | """ 2 | 将学生成绩字典保存为二进制文件,然后读取内容并显示。 3 | """ 4 | import pickle 5 | 6 | filename = ".\习题2_成绩字典.bin" 7 | 8 | def read_dict(): 9 | f = open(filename, 'rb') 10 | score_dict = pickle.load(f) 11 | return score_dict 12 | 13 | def write_dict(score_dict): 14 | f = open(filename, 'wb') 15 | pickle.dump(score_dict, f) 16 | print('已写入', filename) 17 | f.close() 18 | 19 | if __name__ == "__main__": 20 | mode = input('输入模式 r or w:') 21 | if mode == 'w': 22 | score_dict = {'小明':99,'小红':100} 23 | write_dict(score_dict) 24 | else: 25 | print(read_dict()) -------------------------------------------------------------------------------- /01_基础分章节/07_FILE/习题2_成绩字典.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Zaaachary/Python-Foundation-Suda/05d7adabeceff41ce9639c729d2c8b78f4f05467/01_基础分章节/07_FILE/习题2_成绩字典.bin -------------------------------------------------------------------------------- /01_基础分章节/07_FILE/习题3_文件移动.py: -------------------------------------------------------------------------------- 1 | """ 2 | 使用shutil中的move方法进行文件移动 3 | 4 | """ 5 | import shutil 6 | 7 | print('e.g. GBK.txt, ./files') 8 | src = input('请输入要移动的文件或目录:') 9 | dst = input('请输入移动到的位置:') 10 | 11 | shutil.move(src,dst) -------------------------------------------------------------------------------- /01_基础分章节/07_FILE/习题5_修改工作目录.py: -------------------------------------------------------------------------------- 1 | """ 2 | 修改当前工作目录为C"\ 并验证,再修改回来 3 | """ 4 | import os 5 | 6 | cwd = os.getcwd() 7 | print("当前工作目录为:", cwd) 8 | os.chdir("C:\\") 9 | print("已经更改工作目录为:", os.getcwd()) 10 | os.chdir(cwd) 11 | print("已将工作目录改回至:", os.getcwd()) -------------------------------------------------------------------------------- /01_基础分章节/07_FILE/习题6_判断目录中是否存在文件.py: -------------------------------------------------------------------------------- 1 | """ 2 | 用户输入目录和文件名,判断目录及其子目录中是否存在该文件。 3 | """ 4 | 5 | import os 6 | os.chdir('../') 7 | targetpath = input('请输入路径名') 8 | filename = input('请输入文件名:') 9 | 10 | for tup in os.walk(targetpath): 11 | # tup 路径名 路径下的目录列表 路径下的文件列表 12 | if filename in tup[2]: 13 | print("文件存在于",tup[0],"路径下。") 14 | break 15 | else: 16 | print(filename, "下不存在此文件") -------------------------------------------------------------------------------- /01_基础分章节/08_Exception/3.4_Exception_1.py: -------------------------------------------------------------------------------- 1 | # a simple exception program 2 | 3 | k = 0 4 | while k < 3: 5 | try: 6 | x = int(input('please input first interger:')) 7 | y = int(input('please input second interger:')) 8 | print('x/y', x/y) 9 | # except ValueError: 10 | # print('please input a interger! ') 11 | # except ZeroDivisionError: 12 | # print('Division can\'t be zero!') 13 | except(ValueError, ZeroDivisionError)as e: 14 | print('please input a none-zero interger! ', e) 15 | else: 16 | print('no error!') 17 | finally: 18 | print('') 19 | k += 1 20 | 21 | 22 | 23 | 24 | 25 | ''' 26 | 输入非整数会有 ValueError 27 | 输入0会有 ZeroDivisionError 28 | 29 | ''' -------------------------------------------------------------------------------- /01_基础分章节/08_Exception/3.4_Exception_2.py: -------------------------------------------------------------------------------- 1 | # 捕获所有异常 2 | k = 0 3 | while k < 3: 4 | try: 5 | x = int(input('please input first interger:')) 6 | y = int(input('please input second interger:')) 7 | print('x/y', x/y) 8 | except Exception as e: 9 | # except : 10 | print('InputError') 11 | else: 12 | print('no error!') 13 | finally: 14 | print('') 15 | k += 1 16 | 17 | -------------------------------------------------------------------------------- /01_基础分章节/08_Exception/3.4_Exception_3.py: -------------------------------------------------------------------------------- 1 | # 自定义异常类 2 | 3 | 4 | class StrExcept (Exception): # 对应字符串输入错误 5 | pass 6 | 7 | 8 | class MathExcept (Exception): # 对应数值输入异常 9 | pass 10 | 11 | 12 | while True: 13 | try: 14 | x = input('please input your name(2-20 character):') 15 | if len(x) < 2 or len(x) > 20: 16 | raise StrExcept 17 | y = int(input('please input your age( 18-60 ):')) 18 | if y < 18 or y > 60: 19 | raise MathExcept 20 | z = int(input('please input your salary for month( >800):')) 21 | if z < 800: 22 | raise MathExcept 23 | print('姓名:', x) 24 | print('年龄:', y) 25 | print('年收入:', z*12) 26 | break 27 | except StrExcept: 28 | print('name error') 29 | except MathExcept: 30 | print('number error') 31 | except Exception as e: 32 | print('input error', e) 33 | 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /01_基础分章节/08_Exception/3.4_Exception_4.py: -------------------------------------------------------------------------------- 1 | # 求x与y的最大公约数 使用assert 语句来约束x、y取值大于1的正整数 2 | 3 | 4 | while True: 5 | try: 6 | x = int(input('input x :')) 7 | y = int(input('input y :')) 8 | assert x > 1 and y > 1, 'x与y的取值必须大于1' # 断言 9 | a = x 10 | b = y 11 | if a < b: 12 | a,b = b,a 13 | while b!=0: 14 | temp = a%b 15 | a=b 16 | b=temp 17 | else: 18 | print('%s和%s的最大公约数为:%s'%(x,y,a)) 19 | break 20 | except Exception as e: 21 | print('捕捉到异常:\n',e) -------------------------------------------------------------------------------- /01_基础分章节/08_Exception/3.x_file.py: -------------------------------------------------------------------------------- 1 | for i in range(2): 2 | print(i, end='') 3 | for i in range(4, 6): 4 | print(i, end='') -------------------------------------------------------------------------------- /02_MOOC习题/02_0贪心思考题.py: -------------------------------------------------------------------------------- 1 | # 奶茶店促销 2 | # 10元一杯 3杯送1或5杯送2 3 | # 小强带了N元钱(N>=0) 4 | # 请问小强最多可以买多少杯 5 | 6 | # 3送1 3/4*10一杯 5送2 5/7*10 优先5送2 7 | 8 | if __name__ == "__main__": 9 | n = int(input("小强有多少钱:")) 10 | num = n // 10 # 原价能购买的杯数 11 | total = num 12 | if num // 5: 13 | total += num//5 *2 14 | num = num % 5 15 | if num // 3: 16 | total += num//3 17 | print("小明最多可以买{}杯奶茶".format(total)) 18 | -------------------------------------------------------------------------------- /02_MOOC习题/02_1判断正负.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给定一个整数num,判断其正负,返回值为字符串。 3 | 4 | 如果num, > 0, 返回"positive"; 5 | 6 | 如果num, = 0, 返回"zero"; 7 | 8 | 如果num, < 0, 返回"negative" 9 | """ 10 | 11 | 12 | class Solution: 13 | def judge(self, num: int) -> str: 14 | if num > 0: 15 | return "positive" 16 | elif num < 0: 17 | return "negative" 18 | else: 19 | return "zero" 20 | 21 | 22 | 23 | if __name__ == "__main__": 24 | s1 = Solution() 25 | while True: 26 | try: 27 | num = int(input("请输入一个整数")) 28 | print(s1.judge(num)) 29 | except: 30 | break 31 | -------------------------------------------------------------------------------- /02_MOOC习题/02_2判断奇偶.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给定一个整数num,判断其是奇数还是偶数,返回值为字符串 3 | 4 | 如果num是奇数, 返回"odd"; 5 | 6 | 如果num是偶数, 返回"even"; 7 | """ 8 | 9 | 10 | class Solution: 11 | def judge(self, num: int) -> str: 12 | if num % 2 ==0: 13 | return "even" 14 | else: 15 | return "odd" 16 | 17 | 18 | if __name__ == "__main__": 19 | s1 = Solution() 20 | while True: 21 | try: 22 | num = int(input("请输入一个整数")) 23 | print(s1.judge(num)) 24 | except: 25 | break 26 | -------------------------------------------------------------------------------- /02_MOOC习题/02_3判断日期合法.py: -------------------------------------------------------------------------------- 1 | """ 2 | 王老虎的朋友周大牛约王老虎下周一起去看展览, 3 | 但王老虎每周的1、3、5有课必须上课, 4 | 请帮王老虎判断他能否接受周大牛的邀请, 5 | 如果能返回True;如果不能则返回False,如果输入不合法返回None。 6 | 用数字1到7表示从星期一到星期日。 7 | """ 8 | 9 | class Solution: 10 | available = [1,3,5] 11 | def judge(self, num: int): 12 | if num not in range(1,8): # 判断是否在1~7 含头不含尾 13 | return "None" 14 | elif num in self.available: 15 | return "True" 16 | else: 17 | return "False" 18 | 19 | if __name__ == "__main__": 20 | s1=Solution() 21 | while True: 22 | try: 23 | num=int(input("请输入一个整数")) 24 | print(s1.judge(num)) 25 | except: 26 | break -------------------------------------------------------------------------------- /02_MOOC习题/02_4计算邮费.py: -------------------------------------------------------------------------------- 1 | """ 2 | 根据邮件的重量和用户是否选择加急计算邮费。 3 | 计算规则:重量在1000克以内(包括1000克), 基本费8元。 4 | 超过1000克的部分,每500克加收超重费4元,不足500克部分按500克计算; 5 | 如果用户选择加急,多收5元。 6 | 7 | 输入:重量一定是整数,是否加急是一个字符,如果是大写或者小写Y表示加急,否则是不加急。 8 | """ 9 | 10 | 11 | class Solution: 12 | def calc(self, num: int, flag: str) -> int: 13 | total = 8 14 | if flag == "Y" or flag == "y": 15 | total += 5 16 | if num > 1000: 17 | num -= 1000 18 | r = num // 500 19 | if num % 500 != 0: 20 | r += 1 21 | total += r*4 22 | return total 23 | 24 | if __name__ == "__main__": 25 | s1 = Solution() 26 | while True: 27 | try: 28 | num = int(input("请输入重量")) 29 | flag = input("请输入是否加急(Y/N)") 30 | print(s1.calc(num, flag)) 31 | except: 32 | break 33 | -------------------------------------------------------------------------------- /02_MOOC习题/03_0求n的平方根.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | 4 | def bindivide(n: int): 5 | """ 6 | 二分法确定正整数n的平方根 7 | 判断(start+end)/2的平方与n的大小关系 8 | """ 9 | start, end = 0, n 10 | mid = 0 11 | while True: 12 | mid = (start+end)/2 13 | if abs(mid**2 - n) < 1e-6: 14 | break 15 | elif mid**2>n: 16 | end = mid 17 | else: 18 | start = mid 19 | return mid 20 | 21 | def newton(n:int): 22 | # 牛顿迭代法 23 | pass 24 | 25 | 26 | # abs((start+end)/2**2-n) > 1/(10*accruacy) 27 | 28 | if __name__ == "__main__": 29 | n = int(input("输入一个正整数:")) 30 | print("{}的平方根是{}".format(n, math.sqrt(n))) 31 | print(bindivide(n)) 32 | -------------------------------------------------------------------------------- /02_MOOC习题/03_1datetime.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | 3 | def anyd(): 4 | # x年x月x日是星期几 5 | # 方法1 6 | anyday = datetime.datetime(2019,7,17).weekday()+1 7 | print(anyday) 8 | # 方法2 9 | anyday = int(datetime.datetime(2020,2,26).strftime("%w")) 10 | print(anyday) 11 | 12 | 13 | def disx(): 14 | today = datetime.date.today() 15 | d = int(input()) 16 | newday = today + datetime.timedelta(days=d) 17 | print(newday.weekday()+1) 18 | 19 | if __name__ == "__main__": 20 | disx() -------------------------------------------------------------------------------- /02_MOOC习题/03_2谁是罪犯.py: -------------------------------------------------------------------------------- 1 | 2 | def func1(): 3 | values = (0, 1) 4 | candidates = [(A, B, C, D, E) for A in values 5 | for B in values 6 | for C in values 7 | for D in values 8 | for E in values] 9 | 10 | 11 | 12 | def func2(): 13 | # A:not A not C 14 | # B:B or D 15 | # C:A not B 16 | # D:not B 17 | # true * 1 18 | for winner in ('A','B','C','D'): 19 | t = 0 20 | if winner != 'A' and winner != 'C': 21 | t +=1 22 | if winner == 'B' or winner == 'D': 23 | t+=1 24 | else: # B错误 25 | t+=1 26 | if winner == 'A': 27 | t +=1 28 | if t == 1: 29 | print(winner) 30 | break 31 | 32 | if __name__ == "__main__": 33 | func2() -------------------------------------------------------------------------------- /02_MOOC习题/03_3穷举法.py: -------------------------------------------------------------------------------- 1 | # 用穷举法找出1~100之间的勾股数 2 | # 要求:不重复 e.g.345 就不要435 543 3 | # 每行输出5组勾股数 4 | # a^2+b^2=c^2 5 | import math 6 | 7 | def findgg1(start=1, end=100): 8 | l = [] 9 | for i in range(start, end+1): 10 | for j in range(i, end+1): 11 | t = i + j if i + j <=100 else 100 12 | for k in range(i, t): 13 | if i**2 + j**2 == k**2: 14 | l.append((i,j,k)) 15 | print(l) 16 | 17 | def findgg2(start=1, end=100): 18 | l = [] 19 | for i in range(start, end+1): 20 | for j in range(i, end+1): 21 | k = math.sqrt(i**2 + j**2) 22 | if k%1 == 0 and k < 100: 23 | l.append((i,j,int(k))) 24 | print(l) 25 | 26 | 27 | if __name__ == "__main__": 28 | findgg1() 29 | findgg2() 30 | -------------------------------------------------------------------------------- /02_MOOC习题/03_4作业1.py: -------------------------------------------------------------------------------- 1 | """ 2 | 输入n的值,求 3 | 1/1 - 1/2 + 1/3 - 1/4 + 1/5 - 1/6 + 1/7 - 1/8 + ... + (-1)n-1·1/n 的值。 4 | 输入一个正整数n。1 <= n <= 1000。 5 | 返回一个字符串,该字符串的内容是一个保留小数点后四位整数的浮点数 6 | """ 7 | 8 | class Solution: 9 | def calc(self, n: int) -> str: 10 | res = 0 11 | for i in range(1, n+1, 2): 12 | res += 1/i 13 | res -= 1/(i+1) 14 | else: 15 | if n%2!=0: # 奇数时补 16 | res += 1/(n+1) 17 | return ('%0.4f' % res) 18 | 19 | 20 | 21 | 22 | 23 | if __name__ == "__main__": 24 | s1=Solution() 25 | num=int(input("请输入一个整数")) 26 | print(s1.calc(num)) -------------------------------------------------------------------------------- /02_MOOC习题/03_5作业2.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给定一个十进制正整数n,写下从1到n的所有整数,然后数一下其中出现的数字“1”的个数。 3 | 4 | 例如当n=2时,写下1,2。这样只出现了1个“1”; 5 | 当n=12时,写下1,2,3,4,5,6,7,8,9,10,11,12。这样出现了5个“1”。 6 | 7 | 正整数n。1 <= n <= 10000。 8 | """ 9 | 10 | class Solution: 11 | def count(self,n:int)->str: 12 | if not isinstance(n, int) or n>10000 or n <1: 13 | return 14 | res = 0 15 | for i in range(1, n+1): 16 | for ch in str(i): 17 | if ch == '1': 18 | res += 1 19 | print(i, end=',') 20 | return res 21 | 22 | 23 | if __name__ == "__main__": 24 | s1=Solution() 25 | num=int(input("请输入一个整数")) 26 | print(s1.count(num)) -------------------------------------------------------------------------------- /02_MOOC习题/04_0统计字符串.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | f = open("test.txt", 'rt') 4 | data = f.readlines() 5 | f.close() 6 | 7 | dic = dict() 8 | for line in data: 9 | line = line.upper() 10 | for c in line: 11 | if "A" <= c <= "Z": 12 | dic[c] = dic.get(c, 0)+1 13 | 14 | i = 0 15 | for k in sorted(dic): 16 | # 按键排序 17 | print("%s:%d\t"%(k, dic[k]), end='') 18 | i += 1 19 | if i% 4 ==0: 20 | print("") 21 | 22 | i = 0 23 | for k in sorted(dic, key=dic.__getitem__, reverse=True): 24 | # for k in sorted(dic, key=lambda x:dic[x], reverse=True): 25 | # 按值排序 26 | print("%s:%d\t"%(k, dic[k]), end='') 27 | i += 1 28 | if i% 4 ==0: 29 | print("") 30 | -------------------------------------------------------------------------------- /02_MOOC习题/04_1列表与复杂排序思考题.py: -------------------------------------------------------------------------------- 1 | # 对下列文字进行词频统计,再按照词频和字典顺序排序 2 | # 词频主关键字 字典顺序是次关键字 字典顺序不考虑大小写 3 | string = """ 4 | Python includes two operations for sorting. 5 | The method sort() in the built-in list data type 6 | rearranges the items in the underlying list into 7 | ascending order, much like merge.sort(). In contrast, 8 | the built-in function sorted() leaves the underlying 9 | list alone; instead, it returns a new list containing 10 | the items in ascending order. 11 | """ 12 | # string = string.replace('\n', ' ') # 一次只能转换一个 13 | # 生成翻译表 14 | trans_table = ''.maketrans('.,\n()', ' ') 15 | string = string.translate(trans_table) 16 | str_list = string.split() 17 | 18 | str_dict = dict() 19 | for word in str_list: 20 | str_dict[word] = str_dict.get(word, 0) + 1 21 | 22 | # print(str_dict) 23 | str_list = sorted(str_dict, key=lambda s: s.lower()) 24 | str_list.sort(key=lambda s: str_dict[s], reverse=True) 25 | 26 | i = 0 27 | for word in str_list: 28 | print('%s:%d\t'%(word, str_dict[word]), end='') 29 | i += 1 30 | if i % 5 == 0: 31 | print('') 32 | -------------------------------------------------------------------------------- /02_MOOC习题/04_2二分查找.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | def binary_search(L, t, low, high): 4 | while low <= high: 5 | mid = (low + high) // 2 6 | if L[mid] == t: 7 | return True 8 | elif L[mid] < t: 9 | low = mid + 1 10 | else: 11 | high = mid - 1 12 | return False 13 | 14 | 15 | if __name__ == "__main__": 16 | L = [random.randint(0,30) for _ in range(20)] 17 | L.sort() 18 | 19 | print(L) 20 | print(binary_search(L, 14, 0, len(L)-1)) -------------------------------------------------------------------------------- /02_MOOC习题/04_3二分查找思考题.py: -------------------------------------------------------------------------------- 1 | def perfect_square(): 2 | # n是完全平方数,用二分查找计算n的平方根 3 | n = int(input()) 4 | left, right = 1, n//2+1 5 | while left<=right: 6 | mid = (left+right) // 2 7 | temp = mid**2 8 | if temp == n: 9 | print(mid) 10 | return 11 | elif temp > n: 12 | right = mid - 1 13 | else: 14 | left = mid + 1 15 | print("不存在") 16 | return 17 | 18 | def count_sqrt2(): 19 | # 用二分查找计算2的平方根 20 | left, right = 1,2 21 | while left<=right: 22 | mid = (left+right)/2 23 | temp = mid**2 24 | if abs(temp-2) < 1e-10: 25 | print(mid) 26 | return 27 | elif temp > 2: 28 | right = mid 29 | else: 30 | left = mid 31 | return 32 | 33 | 34 | if __name__ == "__main__": 35 | while True: 36 | try: 37 | perfect_square() 38 | except: 39 | break 40 | 41 | count_sqrt2() -------------------------------------------------------------------------------- /02_MOOC习题/04_4自除数.py: -------------------------------------------------------------------------------- 1 | """ 2 | 自除数 是指可以被它包含的每一位数除尽的数。 3 | 4 | 例如,128 是一个自除数, 5 | 因为 128 % 1 == 0,128 % 2 == 0,128 % 8 == 0。 6 | 7 | 还有,自除数不允许包含 0 。 8 | 9 | 给定上边界和下边界数字,输出一个列表, 10 | 列表的元素是边界(含边界)内所有的自除数。 11 | 12 | 示例 1: 13 | 14 | 输入: 15 | 16 | 上边界left = 1, 下边界right = 22 17 | 18 | 输出: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22] 19 | """ 20 | 21 | class Solution: 22 | def selfDividingNumbers(self, left: int, right: int) -> list: 23 | result = [] 24 | for num in range(left, right+1): 25 | num_copy = num 26 | while num_copy != 0: 27 | temp = num_copy % 10 28 | if temp == 0: 29 | break 30 | elif num % temp !=0: 31 | break 32 | num_copy //= 10 33 | else: 34 | result.append(num) 35 | return result 36 | 37 | 38 | 39 | if __name__ == "__main__": 40 | s1=Solution() 41 | left=int(input("请输入一个整数上边界")) 42 | right=int(input("请输入一个整数下边界")) 43 | print(s1.selfDividingNumbers(left,right)) -------------------------------------------------------------------------------- /02_MOOC习题/04_5排序.py: -------------------------------------------------------------------------------- 1 | """ 2 | 非递减顺序数组A,返回每个数字的平方组成的新数组,也按非递减顺序排序 3 | """ 4 | 5 | class Solution: 6 | def sortedSquares(self, A:list) -> list: 7 | B = [pow(i,2) for i in A] 8 | B.sort() 9 | return B 10 | 11 | 12 | 13 | if __name__ == "__main__": 14 | s1 = Solution() 15 | lst = list(map(int, input("请输入n个整数,用空格分开").split())) 16 | print(s1.sortedSquares(lst)) -------------------------------------------------------------------------------- /02_MOOC习题/04_6作业3.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给定一个字符串,你需要反转字符串中每个单词的字符顺序, 3 | 同时仍保留空格和单词的初始顺序。 4 | 5 | 输入: "Let's take LeetCode contest" 6 | 7 | 输出: "s'teL ekat edoCteeL tsetnoc" 8 | 9 | 注意:在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。 10 | """ 11 | 12 | class Solution: 13 | def reverseWords(self, s: str) -> str: 14 | org_list = s.split() 15 | new_list = [] 16 | for word in org_list: 17 | drow = ''.join(reversed(list(word))) 18 | new_list.append(drow) 19 | return new_list 20 | 21 | 22 | 23 | if __name__ == "__main__": 24 | s1 = Solution() 25 | org_str = input("please input an english string:") 26 | print(s1.reverseWords(org_str)) -------------------------------------------------------------------------------- /02_MOOC习题/04_7作业4.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给定一个单词列表,只返回可以使用在键盘同一行的字母打印出来的单词 3 | 4 | """ 5 | 6 | class Solution: 7 | line1 = set('qwertyuiop') 8 | line2 = set('asdfghjkl') 9 | line3 = set('zxcvbnm') 10 | def findWords(self, words: list) -> list: 11 | result_list = [] 12 | for word in words: 13 | word_set = set(word.lower()) 14 | if word_set < self.line1 or word_set < self.line2 or word_set < self.line3: 15 | result_list.append(word) 16 | return result_list 17 | 18 | if __name__ == "__main__": 19 | word_list = input("请在一行输入所有单词,空格分开:").split() 20 | s1 = Solution() 21 | print(s1.findWords(word_list)) 22 | -------------------------------------------------------------------------------- /02_MOOC习题/05_1哥德巴赫.py: -------------------------------------------------------------------------------- 1 | """ 2 | 哥德巴赫猜想:任一大于2的偶数都可以写成2个质数之和 3 | 4 | fast_goldbach (sympy.isprime) 5 | 6 | goldbach 与上作比较 7 | """ 8 | import math 9 | import sympy 10 | from time import perf_counter 11 | 12 | def is_prime(n: int): 13 | # 判断是否是质数 14 | if n >= 2: 15 | for i in range(2, int(math.sqrt(n) + 1)): 16 | if n % i == 0: 17 | return False 18 | return True 19 | else: 20 | # 质数要大于1 21 | return False 22 | 23 | 24 | def goldbach(n: int, speed='D'): 25 | prime = is_prime if speed == 'D' else sympy.isprime 26 | if n <= 2 or n%2 !=0: 27 | print("n must greater than 2 and n%2 == 0") 28 | for p in range(2, n): 29 | q = n - p 30 | if prime(p) and prime(q): 31 | print("{}={}+{}".format(n,p,q)) 32 | break 33 | else: 34 | print("There is something wrong.") 35 | 36 | 37 | if __name__ == "__main__": 38 | while True: 39 | try: 40 | print("="*10) 41 | n = int(input("input n: ")) 42 | mode = input("fast or default F or D: ") 43 | start = perf_counter() 44 | goldbach(n, mode) 45 | print(mode, 'cost:', perf_counter()-start) 46 | except Exception as e: 47 | print(e) 48 | -------------------------------------------------------------------------------- /02_MOOC习题/05_2进制.py: -------------------------------------------------------------------------------- 1 | """ 2 | 实现自己的my_bin() 10转2 3 | “砝码”比较 4 | 5 | 编写my_hex(n) 10->16 6 | hex2bin(n) 16->2 7 | """ 8 | 9 | 10 | def my_bin(n: int): 11 | L = [] # 12 | v = 1 13 | if n < 0: 14 | L.append('-') 15 | n = -n 16 | L.append('0b') 17 | while v <= n//2: 18 | # 找到大于 n//2的最小砝码 19 | v *= 2 20 | while v > 0: 21 | # 判断要不要添加该砝码 22 | if n < v: 23 | L.append('0') 24 | else: 25 | L.append('1') 26 | n -= v 27 | v //= 2 28 | return ''.join(L) 29 | 30 | 31 | def my_hex(n: int): 32 | # 辗转相除法 33 | hex_char = ('0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f') 34 | L = [] 35 | absn = abs(n) 36 | while absn > 0: 37 | L.append(hex_char[absn%16]) 38 | absn //= 16 39 | L.append('0x') 40 | if n < 0: 41 | L.append('-') 42 | L.reverse() 43 | return ''.join(L) 44 | 45 | 46 | def hex2bin(hex_str:str): 47 | """ 48 | • 思路1:先将十六进制转换成十进制,再调用my_bin转成二进制 49 | • 思路2:直接将十六进制转换成二进制 50 | """ 51 | # 思路一 52 | d = int(hex_str, 16) 53 | return my_bin(d) 54 | 55 | 56 | if __name__ == "__main__": 57 | n = int(input()) 58 | print(my_bin(n)) 59 | print(my_hex(n)) 60 | hex_str = input() 61 | print(hex2bin(hex_str)) 62 | -------------------------------------------------------------------------------- /02_MOOC习题/05_3圆周率.py: -------------------------------------------------------------------------------- 1 | import math 2 | import random 3 | 4 | # 严格按照通项 5 | # pi += pow(-1, i)/(2*i+1) 6 | 7 | # 常用表示 8 | # tm = 1 9 | # pi += tm/(2*i+1)*i 10 | # tm = -tm 11 | 12 | 13 | def count_pi1(n: int): 14 | """ 15 | 莱布尼兹级数交错法 16 | pi/4 = sum(o~n) -1^n / (2n+1) 17 | 18 | 结果确定↑ 19 | """ 20 | pi = 0 21 | tm = 1 22 | for i in range(n): 23 | pi += tm/(2*i+1) 24 | tm = -tm 25 | return pi*4 26 | 27 | 28 | def count_pi2(n=100000): 29 | """ 30 | 蒙特卡洛法 31 | 正方形内相切一个圆 随机产生点 32 | 计算点与中心距离是否 小于半径 33 | 点的百分比 = 面积比 pir^2 与r^2 34 | 35 | 每次结算都有所不同↑ 36 | """ 37 | inside = 0 38 | for _ in range(n): 39 | x,y = random.random(),random.random() 40 | if x**2 + y**2 <= 1: 41 | inside += 1 42 | 43 | return inside / n *4 44 | 45 | 46 | if __name__ == "__main__": 47 | for i in [10**i for i in range(1, 8)]: 48 | pi1 = count_pi1(i) 49 | print("count_pi1={},error={:.10f}".format(pi1, math.pi-pi1)) 50 | 51 | sum_dif, k = 0,20 52 | pi2 = 0 53 | for i in range(k): 54 | pi2 += count_pi2() 55 | dif = abs(pi2-math.pi) / pi2 56 | sum_dif += dif 57 | sum_dif /= k 58 | pi2 /= k 59 | print("count_pi2={},error={:.10f}".format(pi2, sum_dif)) 60 | -------------------------------------------------------------------------------- /02_MOOC习题/05_4Base64.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | • 本质上是3字节转4字节 4 | • 3*8=4*6 5 | • 将3字节中数据每次取6 位 6 | • 用6位得到的数值 (0-63)作为索引去查编码表 7 | • 得到编码字符 8 | """ 9 | import string 10 | import base64 11 | 12 | def base64Encode(en_string): 13 | oldBin = '' 14 | tempStr = [] 15 | result = '' 16 | base64_list = string.ascii_uppercase +string.ascii_lowercase \ 17 | + string.digits + '+/' 18 | 19 | # 得到2进制字符串流 ord:返回字符的unicode编码(为了能编码汉字) 20 | for ch in en_string: 21 | temp = int(bin(ord(ch)).replace('0b', '')) 22 | oldBin += '{:08}'.format(temp) # 把数字补到8位 23 | print(oldBin) 24 | 25 | # 切片 使得每6位合并得到字符串 26 | for i in range(0, len(oldBin), 6): 27 | tempStr.append('{:<06}'.format(oldBin[i:i+6])) # 左对齐长6 (补0) 28 | print(tempStr) 29 | 30 | # 字符串装数字后查表,得到编码结果字符串 31 | for item in tempStr: 32 | result += base64_list[int(item, 2)] 33 | print(result) 34 | 35 | 36 | # 补等号 37 | if len(result) % 4 == 2: 38 | result += '==' 39 | elif len(result) % 4 ==3: 40 | result += '=' 41 | 42 | return result 43 | 44 | def testb64module(): 45 | res = base64.b64encode("苏州大学".encode('utf-8')) 46 | print(str(res, 'utf-8')) # res是bytes结构 47 | orgin = base64.b64decode(res) 48 | print(str(orgin, 'utf-8')) 49 | 50 | res = base64.b64encode("苏州大学".encode('gbk')) 51 | print(str(res, 'utf-8')) 52 | orgin = base64.b64decode(res) 53 | print(str(orgin, 'gbk')) 54 | 55 | if __name__ == "__main__": 56 | print(base64Encode(input("请输入要编码的字符串:"))) 57 | testb64module() 58 | -------------------------------------------------------------------------------- /02_MOOC习题/05_5递归.py: -------------------------------------------------------------------------------- 1 | import time 2 | 3 | def my_max(L): 4 | # 计算列表中的最大值 5 | if len(L) == 1: 6 | return L[0] 7 | else: 8 | return max(L[0], my_max(L[1:])) 9 | 10 | 11 | # 递归实现斐波那契 12 | def fibonacci(n): 13 | # F0 = 1 F1=1 Fn = Fn-1 + Fn-2 14 | if n <= 1: 15 | return 1 16 | else: 17 | return fibonacci(n-1) + fibonacci(n-2) 18 | 19 | 20 | # 改进版 一次返回两个值Fn Fn-1 避免重复计算 21 | def fibonacci2(n): 22 | if n<=1: 23 | return (1,1) 24 | else: 25 | (a, b) = fibonacci2(n-1) 26 | return (a+b, a) 27 | 28 | if __name__ == "__main__": 29 | n = int(input()) 30 | start = time.perf_counter() 31 | print(fibonacci(n)) 32 | print("use:",time.perf_counter()-start) 33 | 34 | start = time.perf_counter() 35 | print(fibonacci2(n)[0]) 36 | print("use:",time.perf_counter()-start) 37 | -------------------------------------------------------------------------------- /02_MOOC习题/05_6回文.py: -------------------------------------------------------------------------------- 1 | """ 2 | 如果一个数值字符串顺读和倒读完全一样,称该字符串是回文字 3 | 符串,比如’12321’和’1331’都是回文字符串,’123’则不是。编写 4 | 一个函数使用递归来判断一个数值字符串是否是回文 5 | """ 6 | 7 | def judge_string(ju_str): 8 | if len(ju_str) == 1: 9 | return True 10 | else: 11 | if ju_str[0] != ju_str[-1]: 12 | return False 13 | else: 14 | return judge_string(ju_str[1:-1]) 15 | 16 | if __name__ == "__main__": 17 | s = input() 18 | print(judge_string(s)) -------------------------------------------------------------------------------- /02_MOOC习题/05_作业.py: -------------------------------------------------------------------------------- 1 | """ 2 | 小明将学生排队 学号小到大排一排 然后进行多次调整 3 | 一次调整可能让一名同学出队 向前或先后移动一段距离再入队 4 | 5 | 例: 学生人数8人 6 | 0)初始 1,2,3,4,5,6,7,8 7 | 1)第一次调整 3号向后移动2 1,2,4,5,3,6,7,8 8 | """ 9 | 10 | 11 | class Solution: 12 | def MovingResult(self, m, lst): 13 | """ 14 | m: 学生的数量 15 | lst: 每一个元素是一个元组 元组的第一个元素是学号 第二个是移动的数量 负数表示向前 16 | 返回一个列表 按照顺序存储了当前位置上学生的学号 17 | """ 18 | result = [i+1 for i in range(m)] 19 | for order in lst: 20 | index = result.index(order[0]) 21 | stu = result.pop(index) 22 | index += order[1] 23 | if 0 <= index < m: 24 | result.insert(index, stu) 25 | elif order[1] > 0: 26 | result.append(stu) 27 | elif order[1] < 0: 28 | # 负索引 直接插入在头部 29 | result.insert(0, stu) 30 | return result 31 | 32 | if __name__ == "__main__": 33 | m = 8 34 | lst = [(3, 2), (8, -3), (3, -2)] 35 | s = Solution() 36 | print(s.MovingResult(m, lst)) 37 | -------------------------------------------------------------------------------- /02_MOOC习题/05_作业2.py: -------------------------------------------------------------------------------- 1 | """ 2 | n个小朋友围一圈,小朋友从1~n编号。顺时针方向123...n12 3 | 游戏开始从1号开始顺时针报数,每个小朋友报上个小朋友数+1 4 | 若一个小朋友的数为k的倍数或其个位数为k,则该小朋友出去,不再参加以后的报数 5 | 当游戏中只剩下一个小朋友的时候该小朋友获胜 6 | """ 7 | 8 | 9 | class Solution: 10 | def Circleplay(self, n, k): 11 | player = [i for i in range(n)] 12 | num = 0 13 | current = 0 14 | while len(player) > 1: 15 | num += 1 16 | if num%k == 0 or num%10 ==k: 17 | # 小朋友滚的时候不需要移动current 18 | del player[current] 19 | current = current % len(player) 20 | else: 21 | current = (current+1) % len(player) 22 | return player[0] + 1 # 小朋友是从1开始编号 23 | 24 | if __name__ == "__main__": 25 | test_1 = (5, 2) 26 | test_2 = (7, 3) 27 | 28 | s = Solution() 29 | print(s.Circleplay(*test_1)) 30 | print(s.Circleplay(*test_2)) -------------------------------------------------------------------------------- /02_MOOC习题/05_汽车钥匙模拟题.py: -------------------------------------------------------------------------------- 1 | """ 2 | 模拟整个借还过程 3 | • N个元素的数组表示钥匙盒状态 4 | • 元素值分别初始化成1-N 5 | • 遍历K条借还记录 6 | • 借出-把保存该钥匙的元素置成0 7 | • 返还-把数组第1个为0的元素置成当前钥匙编号 8 | • 顺序输出钥匙盒中的数组中的每个元素 9 | 10 | 两个注意事项: 11 | 1. 返还时刻=借用时刻+使用时间 12 | 2. K条记录不能保证有序返还和借用,需要排序 13 | """ -------------------------------------------------------------------------------- /02_MOOC习题/06_作业/ResultInts.txt: -------------------------------------------------------------------------------- 1 | -123-1212323 2989 2 | 1981 -------------------------------------------------------------------------------- /02_MOOC习题/06_作业/Sort.txt: -------------------------------------------------------------------------------- 1 | 1.3 2 | 2.4 3 | 4.3 4 | 6.5 5 | 10.9 6 | 11.4 7 | 11.4 8 | 12.3 9 | 13.5 10 | 15.2 11 | 16.2 12 | 17.8 13 | avg:10.266666666666667 14 | var:27.160555555555558 15 | -------------------------------------------------------------------------------- /02_MOOC习题/06_作业/cat1.txt: -------------------------------------------------------------------------------- 1 | What is Python? 2 | 3 | Python is an interpreted, interactive, object-oriented programming language. It incorporates modules, exceptions, dynamic typing, very high level dynamic data types, and classes. Python combines remarkable power with very clear syntax. It has interfaces to many system calls and libraries, as well as to various window systems, and is extensible in C or C++. It is also usable as an extension language for applications that need a programmable interface. Finally, Python is portable: it runs on many Unix variants, on the Mac, and on Windows 2000 and later. 4 | To find out more, start with The Python Tutorial. The Beginner’s Guide to Python links to other introductory tutorials and resources for learning Python. 5 | 6 | What is the Python Software Foundation? 7 | 8 | The Python Software Foundation is an independent non-profit organization that holds the copyright on Python versions 2.1 and newer. The PSF’s mission is to advance open source technology related to the Python programming language and to publicize the use of Python. The PSF’s home page is at https://www.python.org/psf/. 9 | Donations to the PSF are tax-exempt in the US. If you use Python and find it helpful, please contribute via the PSF donation page. -------------------------------------------------------------------------------- /02_MOOC习题/06_作业/cat2.txt: -------------------------------------------------------------------------------- 1 | 2 | 3 | What is the Python Software Foundation? 4 | 5 | The Python Software Foundation is an independent non-profit organization that holds the copyright on Python versions 2.1 and newer. The PSF’s mission is to advance open source technology related to the Python programming language and to publicize the use of Python. The PSF’s home page is at https://www.python.org/psf/. 6 | Donations to the PSF are tax-exempt in the US. If you use Python and find it helpful, please contribute via the PSF donation page. -------------------------------------------------------------------------------- /02_MOOC习题/06_作业/numbers.txt: -------------------------------------------------------------------------------- 1 | 12.3 2 | 13.5 3 | 11.4 4 | 11.4 5 | 15.2 6 | 10.9 7 | 6.5 8 | 2.4 9 | 4.3 10 | 17.8 11 | 16.2 12 | 1.3 -------------------------------------------------------------------------------- /02_MOOC习题/06_作业2_提取整数.py: -------------------------------------------------------------------------------- 1 | """ 2 | 附件中有一个文本文件 StrInts.txt,该文件中有一段英文文章,在该文章中存在一些整数(有正有负)。 3 | 编写程序读取该文件、并提取出其中所有的整数,然后将这些整数中 偶数位数字 上全部为 奇数数字 的整数保存到 4 | 当前路径的ResultInts.txt 文件中去,保存时每行 3 个数、每个数占 8 列、右对齐左补空格 5 | """ 6 | import re 7 | 8 | floder = "./06_作业/" 9 | input_path = floder + 'StrInts.txt' 10 | output_path = floder + 'ResultInts.txt' 11 | 12 | 13 | def get_nums(filename): 14 | # 获取数字字符串组成的列表 15 | f = open(filename, 'r', encoding='utf-8') 16 | content = f.read() 17 | f.close() 18 | # 用正则匹配整数 19 | pattern = re.compile(r'-?\d+') 20 | nums = pattern.findall(content) 21 | return nums 22 | 23 | def issatisfy(num_str): 24 | # 判断是否满足偶数位数字全为奇数 25 | # 数字个位为 0 位 e.g. -2 不满足 -12满足 26 | for n in num_str[-1::-2]: 27 | if n not in ('1','3','5','7','9','-'): 28 | return False 29 | else: 30 | return True 31 | 32 | def output_nums(output_path, nums): 33 | # 输出数字到文件 34 | f = open(output_path, 'w') 35 | i = 0 36 | for num in nums: 37 | print(num.rjust(8), end='', file=f) 38 | i += 1 39 | if i % 3 == 0: 40 | f.write('\n') 41 | f.close() 42 | 43 | 44 | if __name__ == "__main__": 45 | nums = get_nums(input_path) 46 | nums = [num for num in nums if issatisfy(num)] # 筛选满足条件的数字 47 | output_nums(output_path, nums) 48 | -------------------------------------------------------------------------------- /02_MOOC习题/06_作业3_数字分析.py: -------------------------------------------------------------------------------- 1 | """ 2 | 附件中有一个文本文件 Numbers.txt,文件中的每一行都是一个浮点数,编写程序读取出所有的浮点数。要求: 3 | 4 | 1 从小到大排序,将排序后的结果写到当前路径下新生成的一个文本文件 5 | Sort.txt 中,每个数占一行。 6 | 7 | 2 求出这些数字的均值、方差,将结果追加写到当前路径下新生成的一个文本 8 | 文件 Sort.txt 中,每个数占一行。 9 | 10 | 3 要求生成的文本文件 Sort.txt 中同时包含排序和均值、方差的结果。 11 | """ 12 | floder = "./06_作业/" 13 | input_path = floder + "Numbers.txt" 14 | output_path = floder + "Sort.txt" 15 | 16 | 17 | def get_nums(filename=input_path): 18 | # 获取浮点数 19 | f = open(filename, 'r') 20 | def trans(x): return float(x.strip()) 21 | nums = list(map(trans, f.readlines())) 22 | f.close() 23 | return nums 24 | 25 | def sort_output(nums, filename=output_path): 26 | # 排序并输出到文件 27 | f = open(filename, 'w') 28 | nums.sort() 29 | for num in nums: 30 | f.write(str(num)+'\n') 31 | f.close() 32 | 33 | def avg_var_output(nums, filename=output_path): 34 | # 计算均值方差并输出 35 | avg = sum(nums)/len(nums) 36 | var = sum([(num - avg)**2 for num in nums])/len(nums) 37 | f = open(filename, 'a') 38 | f.write('avg:'+ str(avg) + '\n') 39 | f.write('var:'+ str(var) + '\n') 40 | f.close() 41 | 42 | if __name__ == "__main__": 43 | nums = get_nums() 44 | sort_output(nums) 45 | avg_var_output(nums) 46 | -------------------------------------------------------------------------------- /02_MOOC习题/06_作业_内容粘贴.py: -------------------------------------------------------------------------------- 1 | """ 2 | 附件中有两个文件cat1.txt和cat2.txt,请编写程序将cat2的内容复制到cat1文件的最后面。 3 | """ 4 | 5 | floder = "./06_作业/" 6 | file1_path = floder + "cat1.txt" 7 | file2_path = floder + "cat2.txt" 8 | 9 | file2 = open(file2_path, 'r') 10 | content = file2.read() 11 | file2.close() 12 | 13 | file1 = open(file1_path, 'a') 14 | file1.write(content) 15 | file1.close() -------------------------------------------------------------------------------- /02_MOOC习题/07_作业1_PM2.5.py: -------------------------------------------------------------------------------- 1 | """ 2 | 实现PM2.5空气质量问题提醒程序,接收用户输入的PM2.5值,合法的值为0-500之间的整数, 3 | 如果PM2.5小于35,打印“空气质量优,建议户外运动”; 4 | 如果PM2.5的值在35到75之间(包括35),打印“空气质量良好,建议适度户外运动”; 5 | 如果PM2.5的值大于75(包括75),打印“空气污染,请小心!” 6 | 7 | 利用 异常处理 用户输入不合法的情况,当用户输入不合法时(输入非整数、输入0-500之外的数值)让用户重新输入。 8 | """ 9 | 10 | 11 | class IllegalInteger(BaseException): 12 | """ 13 | 自定义异常类 接收一个PM值 14 | """ 15 | def __init__(self, num, *args, **kwargs): 16 | super().__init__(*args, **kwargs) 17 | self.num = num 18 | 19 | 20 | def main(): 21 | while True: 22 | # 异常发生时,输出异常信息后会重新进行输入 23 | try: 24 | PM = int(input("请输入当前的PM2.5值:")) 25 | if not (0 < PM <= 500): 26 | # 触发自定义异常 27 | raise IllegalInteger(PM) 28 | except ValueError: 29 | print("请输入一个整数") 30 | except IllegalInteger as x: 31 | print('IllegalInteger:输入的PM值为{}不在0~500的范围'.format(x.num)) 32 | else: 33 | # 未有异常发生则直接打印结果 34 | if PM < 35: 35 | print("空气质量优,建议户外运动") 36 | elif PM < 75: 37 | print("空气质量良好,建议适度户外运动") 38 | else: 39 | print("空气污染,请小心!") 40 | break 41 | 42 | 43 | if __name__ == "__main__": 44 | main() 45 | -------------------------------------------------------------------------------- /03_本科编程题/Files/01_report.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Zaaachary/Python-Foundation-Suda/05d7adabeceff41ce9639c729d2c8b78f4f05467/03_本科编程题/Files/01_report.txt -------------------------------------------------------------------------------- /03_本科编程题/Files/02_string.txt: -------------------------------------------------------------------------------- 1 | Regular296expression913patterns465are280compiled102into510a122series48of563bytecodes16which366are262then773executed361by50a949matching556engine509written126in451C760For379advanced982use201it502may282be666necessary566to631pay199careful685attention915to814how577the455engine309will349execute178a341given171RE279and52write744the69RE578in190a361certain466way726in969order667to310produce943bytecode760that203runs590faster423Optimization723is787not458covered30in250this747document66because396it803requires530that601you928have208a152good609understanding194of31the772matching17engine599internals806 2 | 3 | -------------------------------------------------------------------------------- /03_本科编程题/Files/03_data.txt: -------------------------------------------------------------------------------- 1 | In simple terms, a number is a devic That groups a set of statements so they can be run 2 | more than once in a program, a packaged procedure invoked by name. function also 3 | can compute a result value and let us specify parameters that serve as function inputs 4 | and may difFer each time the code is run. Coding an Operation as a function makes it 5 | -------------------------------------------------------------------------------- /03_本科编程题/Files/03_result.txt: -------------------------------------------------------------------------------- 1 | 6 : 6 -------------------------------------------------------------------------------- /03_本科编程题/Files/03_result1.txt: -------------------------------------------------------------------------------- 1 | 6 : 6 -------------------------------------------------------------------------------- /03_本科编程题/Files/04_result.txt: -------------------------------------------------------------------------------- 1 | 2 3 4 5 6 7 8 9 10 2 | 11 12 13 14 15 16 17 18 19 3 | 20 21 22 -------------------------------------------------------------------------------- /03_本科编程题/Files/ch7_Folder/file1.txt: -------------------------------------------------------------------------------- 1 | file1 2 | -------------------------------------------------------------------------------- /03_本科编程题/Files/ch7_Folder/file2.txt: -------------------------------------------------------------------------------- 1 | file2 2 | -------------------------------------------------------------------------------- /03_本科编程题/Files/ch7_Folder/file3.txt: -------------------------------------------------------------------------------- 1 | file3 -------------------------------------------------------------------------------- /03_本科编程题/Files/ch7_Folder/file4.txt: -------------------------------------------------------------------------------- 1 | file4 -------------------------------------------------------------------------------- /03_本科编程题/Files/ch7_Folder/merge.txt: -------------------------------------------------------------------------------- 1 | file1 2 | file2 3 | file3file4 -------------------------------------------------------------------------------- /03_本科编程题/ch2_484950.py: -------------------------------------------------------------------------------- 1 | 2 | def no48(): 3 | weight = (65.5, 70.2, 100.5, 45.5, 88.8, 55.5, 73.5, 67.8) 4 | 5 | avg = sum(weight) / len(weight) 6 | cov = sum([pow(w-avg, 2) for w in weight]) / len(weight) 7 | 8 | print(cov) 9 | 10 | def no49(dic1, dic2): 11 | for k in dic1: 12 | if k in dic2.keys(): 13 | print(k, end=' ') 14 | 15 | def no50(dic1,dic2): 16 | for v in dic1.values(): 17 | if v in dic2.values(): 18 | print(v, end=' ') 19 | 20 | if __name__ == "__main__": 21 | # 49 22 | # d1 = {1:2, 2:3} 23 | # d2 = {1:3, 3:1} 24 | # no49(d1,d2) 25 | 26 | # 50 27 | # d1 = {1:2, 2:3} 28 | # d2 = {1:3, 3:1} 29 | # no50(d1,d2) 30 | 31 | pass -------------------------------------------------------------------------------- /03_本科编程题/ch2_51menber.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | if __name__ == "__main__": 4 | menber = {} 5 | while True: 6 | try: 7 | name, number = input("请输入一个姓名,编号:").split(',') 8 | menber[number] = name 9 | except Exception as e: 10 | for num,name in menber.items(): 11 | print(name, num) 12 | for num,name in menber.items(): 13 | print(num, name) 14 | -------------------------------------------------------------------------------- /03_本科编程题/ch7_54copy.py: -------------------------------------------------------------------------------- 1 | 2 | import shutil 3 | 4 | def copy_file(filename='ch7_54_copy.txt'): 5 | shutil.copyfile(filename, 'ch7_54_new.txt') 6 | 7 | if __name__ == "__main__": 8 | copy_file() -------------------------------------------------------------------------------- /03_本科编程题/ch7_55sort.py: -------------------------------------------------------------------------------- 1 | """ 2 | 55.【文件】当前路径下有文本文件 Numbers.txt,文件中的每一行都是一个浮 3 | 点数,编写程序读取出所有的浮点数。要求: 4 | a) 从小到大排序,将排序后的结果写到当前路径下新生成的一个文本文件 5 | Sort.txt 中,每个数占一行。 6 | b) 求出这些数字的均值、方差,将结果写到当前路径下新生成的一个文本 7 | 文件 Sort.txt 中,每个数占一行。 8 | c) 要求生成的文本文件 Sort.txt 中同时包含排序和均值、方差的结果。 9 | 10 | """ 11 | def read_num(filename="ch7_55_Numbers.txt"): 12 | f = open(filename, 'r') 13 | num_list = list(map(float, f.readlines())) 14 | return num_list 15 | 16 | 17 | def sort_num(num_list: list): 18 | num_list.sort() 19 | 20 | def comput_avg_cov(num_list): 21 | avg = sum(num_list) 22 | cov = sum([(num - avg)**2 for num in num_list])/len(num_list) 23 | return avg, cov 24 | 25 | def save_result(filename="ch7_55_Sort.txt", **kwarg): 26 | f = open(filename, 'a+') 27 | for _, v in kwarg.items(): 28 | if isinstance(v,list): 29 | for i in v: 30 | f.write(str(i)+'\n') 31 | else: 32 | f.write(str(v)+'\n') 33 | f.write('\n') 34 | 35 | f.close() 36 | 37 | 38 | if __name__ == "__main__": 39 | num_list = read_num() 40 | 41 | sort_num(num_list) 42 | save_result(num_list=num_list) 43 | 44 | a,c = comput_avg_cov(num_list) 45 | print(a,c) 46 | save_result(avg=a, cov=c) -------------------------------------------------------------------------------- /03_本科编程题/ch7_56merge.py: -------------------------------------------------------------------------------- 1 | from os import path 2 | 3 | def read_files(Folder='ch7_Folder'): 4 | total_content = [] 5 | for i in range(1,5): 6 | p = path.join(Folder, 'file{}.txt'.format(i)) 7 | f = open(p,'r') 8 | content = f.readlines() 9 | total_content.extend(content) 10 | f.close() 11 | return total_content 12 | 13 | def write_merge(content, Folder='ch7_Folder'): 14 | p = path.join(Folder, 'merge.txt') 15 | f = open(p, 'w') 16 | f.writelines(content) 17 | f.close() 18 | 19 | if __name__ == "__main__": 20 | content = read_files() 21 | write_merge(content) -------------------------------------------------------------------------------- /03_本科编程题/ch7_57_word.py: -------------------------------------------------------------------------------- 1 | """ 2 | 当前路径下有文本文件 word.txt 中包含了 20 个英文单词,编写一 3 | 个程序,删除文件中所有不以元音开头的单词。结果保存在当前路径下新生 4 | 成的 new_word.txt 中。 5 | """ 6 | 7 | target = 'aeiouAEIOU' 8 | 9 | if __name__ == "__main__": 10 | f = open('ch7_57_word.txt', 'r') 11 | word_list = f.read().split() 12 | f.close() 13 | 14 | for word in word_list[::]: 15 | if word[0] not in target: 16 | word_list.remove(word) 17 | 18 | f = open('ch7_57_newword.txt', 'w') 19 | for word in word_list: 20 | f.write(word+'\n') 21 | f.close() -------------------------------------------------------------------------------- /03_本科编程题/ch7_58Names.py: -------------------------------------------------------------------------------- 1 | """ 2 | 当前路径下有一个文本文件Names.txt 3 | 包含了按照字典排序的名字 4 | 编写一个程序,当用户自己给定一个名字, 5 | 按照字典序将其插入到正确的位置 6 | 如果这个名字已经存在于文件中,则不要插入。 7 | 8 | 难点:文件的插入 9 | """ 10 | 11 | def read_names(filename="ch7_58_Names.txt"): 12 | f = open(filename, 'r') 13 | name_list = list(map(lambda x: x.strip(),f.readlines())) 14 | f.close() 15 | return name_list 16 | 17 | def insert_name(name_list:list, newname): 18 | i = 0 19 | for name in name_list: 20 | if name < newname: 21 | i += 1 22 | continue 23 | elif name == newname: 24 | return 25 | else: 26 | break 27 | name_list.insert(i, newname) 28 | 29 | def write_names(name_list, filename="ch7_58_new_word.txt"): 30 | f = open(filename, 'w') 31 | for name in name_list: 32 | f.write(name+'\n') 33 | f.close() 34 | 35 | if __name__ == "__main__": 36 | name_list = read_names() 37 | print(name_list) 38 | newname = input("please input a new name:") 39 | insert_name(name_list, newname) 40 | print(name_list) 41 | write_names(name_list) -------------------------------------------------------------------------------- /03_本科编程题/ch7_59_largefile.py: -------------------------------------------------------------------------------- 1 | """ 2 | 有一个 100G 的文件 largefile.txt(这个文件目前没有 3 | 100G,只是做模拟)。 4 | 实现一个程序,首先输出 largefile.txt 的行数,然后 5 | 无限循环,每次要求用户键盘输入一个行号,然后立刻输出对应行的文本。 6 | 由于文件很大,不允许将文件内容全部放到内存中; 7 | 同时也不允许从头扫描文件,得到对应行的文本,因为这样速度太慢。 8 | (提示:用二进制模式打开文件,使用 tell, seek 等方法) 9 | """ 10 | 11 | def read_in_block(file_path=r'Data\01_data.txt'): 12 | block_size = 16 13 | with open(file_path, 'rb') as f: 14 | while True: 15 | block = f.read(block_size) 16 | if block: 17 | yield block 18 | else: 19 | return 20 | 21 | def count_line(file_generator): 22 | line_dict = {1:0} 23 | line = 1 24 | location = 0 25 | for block in file_generator: 26 | temp = 0 27 | for bytech in block: 28 | if bytech == 10: 29 | line += 1 30 | line_dict[line] = location+temp+1 31 | temp += 1 32 | location += 16 33 | return line, line_dict 34 | 35 | def read_location(line, line_dict, file_path=r'Data\01_data.txt'): 36 | f = open(file_path, 'r') 37 | f.seek(line_dict[line]) 38 | string = f.readline() 39 | print(string) 40 | f.close() 41 | 42 | if __name__ == "__main__": 43 | file_generator = read_in_block() 44 | l,ld = count_line(file_generator) 45 | print("共{}行".format(l)) 46 | while True: 47 | try: 48 | line = int(input("输入行号")) 49 | read_location(line, ld) 50 | except Exception as e: 51 | print(e) 52 | -------------------------------------------------------------------------------- /03_本科编程题/题目/01_2016年期末.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Zaaachary/Python-Foundation-Suda/05d7adabeceff41ce9639c729d2c8b78f4f05467/03_本科编程题/题目/01_2016年期末.pdf -------------------------------------------------------------------------------- /03_本科编程题/题目/02_2016年期中.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Zaaachary/Python-Foundation-Suda/05d7adabeceff41ce9639c729d2c8b78f4f05467/03_本科编程题/题目/02_2016年期中.pdf -------------------------------------------------------------------------------- /03_本科编程题/题目/03_2017年1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Zaaachary/Python-Foundation-Suda/05d7adabeceff41ce9639c729d2c8b78f4f05467/03_本科编程题/题目/03_2017年1.pdf -------------------------------------------------------------------------------- /03_本科编程题/题目/04_2017年2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Zaaachary/Python-Foundation-Suda/05d7adabeceff41ce9639c729d2c8b78f4f05467/03_本科编程题/题目/04_2017年2.pdf -------------------------------------------------------------------------------- /03_本科编程题/题目/05_2018年.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Zaaachary/Python-Foundation-Suda/05d7adabeceff41ce9639c729d2c8b78f4f05467/03_本科编程题/题目/05_2018年.pdf -------------------------------------------------------------------------------- /03_本科编程题/题目/06_2019年.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Zaaachary/Python-Foundation-Suda/05d7adabeceff41ce9639c729d2c8b78f4f05467/03_本科编程题/题目/06_2019年.pdf -------------------------------------------------------------------------------- /03_本科编程题/题目/Python编程习题集chxx.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Zaaachary/Python-Foundation-Suda/05d7adabeceff41ce9639c729d2c8b78f4f05467/03_本科编程题/题目/Python编程习题集chxx.pdf -------------------------------------------------------------------------------- /04_历年复试真题/2016_词频统计.py: -------------------------------------------------------------------------------- 1 | r""" 2 | 2016 3 | 要求: 4 | 文本文件 input.txt 由若干英文单词和分隔符(空格,回车,换行)构成. 根据如下说明编写程序统计不同单词出现 5 | 的次数(频度). 将统计结果按出现频度从高到低排序,并将出现频度大于 5 的单词及其频度输出到文件 output.txt 6 | 中. 文件格式如下所示: 7 | WinEdt, 31 8 | 1. 多个连续的分隔符被视为一个分隔符 9 | 2. 单词大小写敏感 10 | 3. 每个单词的长度不超过20个字符 11 | 4. 单词的数量未知 12 | """ 13 | 14 | 15 | def read_str(filename="2016_input.txt"): 16 | f = open(filename, 'r') 17 | lines = f.readlines() 18 | f.close() 19 | content = ' '.join(lines) # 连接不同行 20 | return content 21 | 22 | def count_word(content): 23 | # 字典实现 24 | freq_dict = {} 25 | str_list = content.split() 26 | for word in str_list: 27 | freq_dict[word] = freq_dict.get(word, 0) + 1 28 | 29 | # 集合实现 30 | # word_set = list(set(content)) 31 | # count = [] 32 | # for word in word_set: 33 | # count.append(content.count(word)) 34 | # word_count_list = list(zip(word_set, count)) 35 | # word_count_list.sort(key = lambda x : x[1], reverse = True) 36 | 37 | return freq_dict 38 | 39 | def output_file(freq:dict, filename="2016_output.txt"): 40 | f = open(filename, 'w') 41 | word_list = list(filter(lambda x: True if freq[x]>5 else False, freq.keys())) 42 | word_list.sort(key=lambda x:freq[x], reverse=True) # 频度从大到小排序 43 | for word in word_list: 44 | f.write('{0},{1}\n'.format(word, freq[word])) 45 | f.close() 46 | 47 | if __name__ == "__main__": 48 | content = read_str() 49 | freq_dict = count_word(content) 50 | output_file(freq_dict) 51 | -------------------------------------------------------------------------------- /04_历年复试真题/2018_.py: -------------------------------------------------------------------------------- 1 | """ 2 | 读取一个二进制数,里面有20k个数字。 3 | 求一个最大子集,将其写入到一个文件。 4 | 1. 最大子集任意两个数字之间不成倍数,且最大公约数为1 5 | 2. 按格式输入到一个文件中 6 | 格式:第一行为总个数 7 | 12 8 | 2 3 5 7 13 9 | 17 23 29 31 37 10 | 41 43 11 | """ 12 | 13 | def writetestnum(filename="2018_data.bin"): 14 | import random 15 | f = open(filename, 'wb') 16 | num_list = [random.randint(1,100) for _ in range(200)] 17 | i = 0 18 | while i < 200: 19 | temp = random.randint(1,15) 20 | if 200-i < temp: 21 | temp = 200-i 22 | f.write(bytes(str(temp)+'\n',encoding='gbk')) 23 | for _ in range(temp): 24 | f.write(bytes(str(num_list[i])+' ',encoding='gbk')) 25 | i += 1 26 | f.write(b'\n') 27 | 28 | 29 | 30 | def readnum(filename="2018_data.bin"): 31 | f = open(filename, 'rb') 32 | bytestr = f.read() 33 | f.close() 34 | content = bytestr.decode('gbk','ignore') 35 | num_list = content.split() 36 | return num_list 37 | 38 | 39 | def groupnum(num_list): 40 | pass 41 | 42 | 43 | if __name__ == "__main__": 44 | # writetestnum() 45 | num_list = readnum()[:30] -------------------------------------------------------------------------------- /04_历年复试真题/2021_四道编程题/2021_四道题目.txt: -------------------------------------------------------------------------------- 1 | 2021 苏州大学计算机复试上机编程题 2 | 3 | 4 | 1. 输入n 找出1~n 中 二进制1比0多的数,升序返回 5 | 2. 查找一个数列中两个数相乘最大,如果两个pair 都是最大的就是相加起来最大的那个,返回元组,里边的元素先小后大 6 | 3. 查找某一个数后面离它最近的比他大的数,如果没有就是none 7 | [1,3,5] [3,5,none] 8 | [7,3,5] [none,5,none] 9 | 4. 数组包含很多集合,集合都是一些数字, 然后返回集合 出现频率大于 [数组长度/2](下标) [{1,2},{1,2,3}] 10 | -------------------------------------------------------------------------------- /04_历年复试真题/2021_四道编程题/26239 _1.py: -------------------------------------------------------------------------------- 1 | 2 | # 输入n 找出1~n 中 二进制1比0多的数 3 | 4 | def find_number(n): 5 | a=[] 6 | for i in range(1,n+1): 7 | s=bin(i)[2:] 8 | if s.count('1')>s.count('0'): 9 | a.append(i) 10 | return a 11 | 12 | if __name__ == "__main__": 13 | pass -------------------------------------------------------------------------------- /04_历年复试真题/2021_四道编程题/26239_2.py: -------------------------------------------------------------------------------- 1 | 2 | # 查找一个数列中两个数相乘最大,如果两个pair 都是最大的就是相加起来最大的那个 3 | def find_pair(L): 4 | if len(L) < 2: 5 | return[] 6 | x = L[0] 7 | y = L[1] 8 | m = L[0]*L[1] 9 | for index, i in enumerate(L): 10 | for j in L[index+1:]: 11 | c = i*j 12 | if c > m: 13 | x = i 14 | y = j 15 | m = c 16 | if c == m: 17 | if i+j > x+y: 18 | x, y = i, j 19 | if x > y: 20 | x, y = y, x 21 | return (x, y) 22 | -------------------------------------------------------------------------------- /04_历年复试真题/2021_四道编程题/26239_3.py: -------------------------------------------------------------------------------- 1 | 2 | #查找某一个数后面离它最近的比他大的数,如果没有就是none 3 | #[1,3,5] [3,5,none] 4 | #[7,3,5] [none,5,none] 5 | def find_next(L): 6 | a=[None]*len(L) 7 | for index,i in enumerate(L): 8 | for j in L[index+1:]: 9 | if j>i: 10 | a[index]=j 11 | break 12 | return a 13 | 14 | -------------------------------------------------------------------------------- /04_历年复试真题/2021_四道编程题/26239_4.py: -------------------------------------------------------------------------------- 1 | 2 | # [{1,2},{1,2,3}] 3 | # 数组包含很多集合,集合都是一些数字, 然后返回数字 出现频率大于 [数组长度/2](下标) 4 | def find_major(L): 5 | s = len(L)//2 6 | m = {} 7 | result = set() 8 | for i in L: 9 | for j in i: 10 | m[j] = m.get(j, 0)+1 11 | for key, value in m.items(): 12 | if value > s: 13 | result.add(key) 14 | if len(result) == 0: 15 | return None 16 | return result 17 | 18 | 19 | if __name__ == "__main__": 20 | pass 21 | -------------------------------------------------------------------------------- /04_历年复试真题/Data/03_data.txt: -------------------------------------------------------------------------------- 1 | In simple terms, a number is a devic That groups a set of statements so they can be run 2 | more than once in a program, a packaged procedure invoked by name. function also 3 | can compute a result value and let us specify parameters that serve as function inputs 4 | and may difFer each time the code is run. Coding an Operation as a function makes it 5 | -------------------------------------------------------------------------------- /04_历年复试真题/Data/03_result: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Zaaachary/Python-Foundation-Suda/05d7adabeceff41ce9639c729d2c8b78f4f05467/04_历年复试真题/Data/03_result -------------------------------------------------------------------------------- /04_历年复试真题/Data/03_result.txt: -------------------------------------------------------------------------------- 1 | 6 : 6 -------------------------------------------------------------------------------- /04_历年复试真题/Data/2016_output.txt: -------------------------------------------------------------------------------- 1 | a,35 2 | function,15 3 | is,10 4 | can,10 5 | and,10 6 | as,10 7 | -------------------------------------------------------------------------------- /04_历年复试真题/Data/2017_data.bin: -------------------------------------------------------------------------------- 1 | 12,34,53,25,61,28,78 -------------------------------------------------------------------------------- /04_历年复试真题/Data/2018_data.bin: -------------------------------------------------------------------------------- 1 | 3 2 | 73 74 88 3 | 7 4 | 20 10 12 41 54 62 46 5 | 15 6 | 1 28 20 69 93 40 2 8 6 43 61 72 26 39 18 7 | 4 8 | 100 55 47 69 9 | 13 10 | 62 95 80 61 49 73 28 34 27 96 63 58 89 11 | 8 12 | 74 85 49 30 15 34 33 40 13 | 12 14 | 22 57 35 99 24 66 1 64 1 36 54 69 15 | 6 16 | 43 44 29 85 19 52 17 | 10 18 | 85 48 70 45 7 31 84 77 1 41 19 | 8 20 | 55 83 38 35 81 74 50 57 21 | 9 22 | 12 45 16 48 84 20 69 88 82 23 | 4 24 | 54 86 72 16 25 | 14 26 | 68 24 34 36 38 18 75 3 53 10 28 51 87 57 27 | 3 28 | 24 47 81 29 | 6 30 | 88 57 27 25 5 37 31 | 4 32 | 38 79 28 11 33 | 9 34 | 61 10 24 71 64 65 78 62 60 35 | 2 36 | 30 84 37 | 14 38 | 89 97 63 16 13 23 1 96 64 15 37 28 60 52 39 | 4 40 | 35 28 27 54 41 | 10 42 | 35 89 57 45 36 27 26 68 48 47 43 | 7 44 | 78 71 69 86 10 54 47 45 | 11 46 | 6 22 72 97 13 59 96 40 36 27 63 47 | 3 48 | 38 1 5 49 | 1 50 | 14 51 | 5 52 | 7 13 66 28 95 53 | 8 54 | 29 67 85 74 12 40 88 53 55 | -------------------------------------------------------------------------------- /04_历年复试真题/Data/ch7_54_copy.txt: -------------------------------------------------------------------------------- 1 | 54 txt -------------------------------------------------------------------------------- /04_历年复试真题/Data/ch7_54_new.txt: -------------------------------------------------------------------------------- 1 | 54 txt -------------------------------------------------------------------------------- /04_历年复试真题/Data/ch7_55_Numbers.txt: -------------------------------------------------------------------------------- 1 | 2321.24125 2 | 2324.2314 3 | 53467.345 4 | 2425154.2 5 | 13124.21 6 | 52342.123 -------------------------------------------------------------------------------- /04_历年复试真题/Data/ch7_55_Sort.txt: -------------------------------------------------------------------------------- 1 | 2321.24125 2 | 2324.2314 3 | 13124.21 4 | 52342.123 5 | 53467.345 6 | 2425154.2 7 | 8 | 2548733.3506500004 9 | 5311886859093.687 10 | 11 | -------------------------------------------------------------------------------- /04_历年复试真题/Data/ch7_57_newword.txt: -------------------------------------------------------------------------------- 1 | Aaron 2 | -------------------------------------------------------------------------------- /04_历年复试真题/Data/ch7_57_word.txt: -------------------------------------------------------------------------------- 1 | Aaron 2 | Billy 3 | Cornell 4 | Sandy 5 | Zachary 6 | -------------------------------------------------------------------------------- /04_历年复试真题/Data/ch7_58_Names.txt: -------------------------------------------------------------------------------- 1 | Aaron 2 | Billy 3 | Cornell 4 | Sandy 5 | Zachary 6 | -------------------------------------------------------------------------------- /04_历年复试真题/Data/ch7_58_new_word.txt: -------------------------------------------------------------------------------- 1 | Aaron 2 | Billy 3 | Cornell 4 | Sandy 5 | Zachary 6 | -------------------------------------------------------------------------------- /05_leetcode/1.两数之和.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给定一个整数数组 nums 和一个目标值 target, 3 | 请你在该数组中找出和为 目标值 的那 两个 整数,并返回他们的数组 下标。 4 | 5 | 你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。 6 | """ 7 | 8 | 9 | class Solution: 10 | def twoSum(self, nums: list, target: int) -> list: 11 | for index, num in enumerate(nums): 12 | temp = target - num 13 | try: 14 | index2 = nums.index(temp) 15 | except: 16 | continue 17 | if index == index2: 18 | continue 19 | return [index, index2] 20 | 21 | def twoSum2(self, nums: list, target: int) -> list: 22 | num_dict = {} 23 | for index, num in enumerate(nums): 24 | temp = target - num 25 | if temp in num_dict: 26 | return num_dict[temp], index 27 | else: 28 | num_dict[num] = index 29 | 30 | 31 | if __name__ == "__main__": 32 | s = Solution() 33 | nums = [2, 7, 11, 15] 34 | target = 9 35 | print(s.twoSum(nums, target)) 36 | -------------------------------------------------------------------------------- /05_leetcode/1002.查找常用字符.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给定仅有小写字母组成的字符串数组 A, 3 | 4 | 返回列表中的每个字符串中都显示的 全部字符(包括重复字符)组成的列表。 5 | 6 | ??? 7 | 例如,如果一个字符在每个字符串中出现 3 次,但不是 4 次, 8 | 9 | 则需要在最终答案中包含该字符 3 次。 10 | 11 | 你可以按任意顺序返回答案。 12 | 13 | 来源:力扣(LeetCode) 14 | 链接:https://leetcode-cn.com/problems/find-common-characters 15 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 16 | """ 17 | 18 | class Solution: 19 | def commonChars(self, A: list) -> list: 20 | result = [] 21 | ch_dict = {} 22 | for ch in A[0]: 23 | ch_dict[ch] = ch_dict.get(ch, 0) + 1 24 | 25 | for s in A: 26 | del_key = [] 27 | for key, value in ch_dict.items(): 28 | k_num = s.count(key) 29 | if 0< k_num < value: 30 | ch_dict[key] = k_num 31 | elif k_num == 0: 32 | del_key.append(key) 33 | for key in del_key: 34 | ch_dict.pop(key) 35 | 36 | for k, v in ch_dict.items(): 37 | result.extend([k] * v) 38 | 39 | return result 40 | 41 | def commonChars2(self, A: list) -> list: 42 | result = [] 43 | for w in set(A[0]): 44 | # 计算w字符在整个A中的出现次数 45 | count = [s.count(w) for s in A] 46 | result.extend([w]*min(count)) 47 | 48 | return result 49 | 50 | if __name__ == "__main__": 51 | test = ["bella","label","roller"] 52 | s = Solution() 53 | print(s.commonChars(test)) -------------------------------------------------------------------------------- /05_leetcode/1025.除数博弈.py: -------------------------------------------------------------------------------- 1 | """ 2 | 爱丽丝和鲍勃一起玩游戏,他们轮流行动。爱丽丝先手开局。 3 | 4 | 最初,黑板上有一个数字 N 。在每个玩家的回合,玩家需要执行以下操作: 5 | 6 | - 选出任一 x,满足 0 < x < N 且 N % x == 0 。 7 | - 用 N - x 替换黑板上的数字 N 。 8 | 9 | 如果玩家无法执行这些操作,就会输掉游戏。 10 | 11 | 只有在爱丽丝在游戏中取得胜利时才返回 True,否则返回 false。假设两个玩家都以 最佳状态 参与游戏。 12 | """ 13 | 14 | class Solution: 15 | def divisorGame(self, N: int) -> bool: 16 | # 可以证明N为偶数时 爱丽丝必胜 17 | return N%2 == 0 18 | 19 | if __name__ == "__main__": 20 | S = Solution() 21 | print(S.divisorGame(4)) -------------------------------------------------------------------------------- /05_leetcode/104.二叉树的最大深度.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给定一个二叉树,找出其最大深度。 3 | 4 | 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。 5 | 6 | 说明: 叶子节点是指没有子节点的节点。 7 | 8 | 示例: 9 | 给定二叉树 [3,9,20,null,null,15,7], 10 | 最大深度3 11 | """ 12 | # Definition for a binary tree node. 13 | class TreeNode: 14 | def __init__(self, x): 15 | self.val = x 16 | self.left = None 17 | self.right = None 18 | 19 | class Solution: 20 | def maxDepth(self, root: TreeNode) -> int: 21 | if not root: 22 | return 0 23 | else: 24 | return max(self.maxDepth(root.left), self.maxDepth(root.right))+1 -------------------------------------------------------------------------------- /05_leetcode/1046.最后一块石头的重量.py: -------------------------------------------------------------------------------- 1 | """ 2 | 有一堆石头,每块石头的重量都是正整数。 3 | 4 | 每一回合,从中选出两块最重的石头,然后将它们一起粉碎。 5 | 假设石头的重量分别为 x 和 y,且 x <= y。那么粉碎的可能结果如下: 6 | 7 | 如果 x == y,那么两块石头都会被 完全粉碎; 8 | 如果 x != y,那么重量为 x 的石头将会 完全粉碎 ,而重量为 y 的石头新重量为 y-x。 9 | 最后,最多只会剩下一块石头。返回此石头的重量。如果没有石头剩下,就返回 0。 10 | 11 | 来源:力扣(LeetCode) 12 | 链接:https://leetcode-cn.com/problems/last-stone-weight 13 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 14 | """ 15 | 16 | 17 | class Solution: 18 | def lastStoneWeight(self, stones: list) -> int: 19 | while len(stones) > 1: 20 | stones.sort(reverse=True) 21 | y = stones.pop(0) 22 | x = stones.pop(0) 23 | if x == y: 24 | continue 25 | else: 26 | stones.append(y-x) 27 | if len(stones) == 1: 28 | return stones[0] 29 | elif len(stones) == 0: 30 | return 0 31 | 32 | 33 | if __name__ == '__main__': 34 | stones = [1, 425, 63, 4, 13] 35 | s1 = Solution() 36 | print(s1.lastStoneWeight(stones)) 37 | -------------------------------------------------------------------------------- /05_leetcode/11.!!双指针_盛水最多的容器.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给你 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。 3 | 在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。 4 | 找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。 5 | 6 | 说明:你不能倾斜容器,且 n 的值至少为 2。 7 | 8 | 图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。 9 | """ 10 | 11 | class Solution: 12 | def maxArea(self, height: list) -> int: 13 | # 超时 N^2 暴力 14 | maxA = 0 15 | for i in range(len(height)-1): 16 | for j in range(i + 1, len(height)): 17 | tempA = (j-i) * min(height[i], height[j]) 18 | maxA = max(tempA, maxA) 19 | return maxA 20 | 21 | def maxArea2(self, height): 22 | # 72ms 74.45% 23 | # 双指针 每次移动小的一边(无论怎么移动大的容量都不会变大 缩减问题边界) 24 | left, right = 0, len(height) - 1 25 | ans = 0 26 | while left < right: 27 | area = min(height[left], height[right]) * (right - left) 28 | ans = max(ans, area) 29 | if height[left] <= height[right]: 30 | left += 1 31 | else: 32 | right -= 1 33 | return ans 34 | 35 | if __name__ == "__main__": 36 | S = Solution() 37 | print(S.maxArea([1,8,6,2,5,4,8,3,7])) -------------------------------------------------------------------------------- /05_leetcode/118.!杨辉三角.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。 3 | 4 | 5 | """ 6 | 7 | class Solution: 8 | def generate(self, numRows: int): 9 | lines = [] 10 | for row_num in range(numRows): 11 | row = [] 12 | if row_num == 0: 13 | row.append(1) 14 | else: 15 | row.append(1) 16 | for i in range(row_num // 2): 17 | # 计算上一行对应位置数量和 18 | row.append(lines[row_num-1][i]+lines[row_num-1][i+1]) 19 | if row_num % 2 == 0: 20 | row.extend(reversed(row[0:-1])) 21 | else: 22 | row.extend(reversed(row)) 23 | lines.append(row) 24 | return lines 25 | 26 | def generate2(self, numRows: int): 27 | """ 28 | 29 | 前一行首尾添0 形成两个列表 然后本行等于这两个列表逐位相加 30 | """ 31 | if numRows == 0: 32 | return [] 33 | 34 | res = [[1]] 35 | while len(res) < numRows: 36 | newRow = [a+b for a, b in zip([0]+res[-1], res[-1]+[0])] 37 | res.append(newRow) 38 | return res 39 | 40 | 41 | 42 | if __name__ == "__main__": 43 | test = 5 44 | s1 = Solution() 45 | print(s1.generate(test)) -------------------------------------------------------------------------------- /05_leetcode/1184.公交站间的距离.py: -------------------------------------------------------------------------------- 1 | """ 2 | 环形公交路线上有 n 个站,按次序从 0 到 n - 1 进行编号。 3 | 4 | 我们已知每一对相邻公交站之间的距离,distance[i] 表示编号为 i 的车站和编号为 (i + 1) % n 的车站之间的距离。 5 | 6 | 环线上的公交车都可以按 顺时针和逆时针 的方向行驶。 7 | 8 | 返回乘客从出发点 start 到目的地 destination 之间的最短距离。 9 | 10 | 来源:力扣(LeetCode) 11 | 链接:https://leetcode-cn.com/problems/distance-between-bus-stops 12 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 13 | """ 14 | from typing import List 15 | class Solution: 16 | def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int: 17 | # 68ms 30% 18 | d1, d2 = 0, 0 19 | if start > destination: 20 | start, destination = destination, start 21 | d1 = sum(distance[:start]) + sum(distance[destination:]) 22 | d2 = sum(distance[start:destination]) 23 | return min(d1, d2) 24 | 25 | def distanceBetweenBusStops2(self, distance, start, destination): 26 | sum_distance = sum(distance) 27 | if start <= destination: 28 | first_distance = sum(distance[start:destination]) 29 | else: 30 | first_distance = sum(distance[destination:start]) 31 | return min(first_distance, sum_distance-first_distance) 32 | 33 | 34 | if __name__ == "__main__": 35 | distance = [1,2,3,4] 36 | start = 0 37 | destination = 1 38 | S = Solution() 39 | print(S.distanceBetweenBusStops(distance, start, destination)) -------------------------------------------------------------------------------- /05_leetcode/1252.奇数值单元格的数目.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给你一个 n 行 m 列的矩阵,最开始的时候,每个单元格中的值都是 0。 3 | 4 | 另有一个索引数组 indices,indices[i] = [ri, ci] 中的 5 | 6 |  ri 和 ci 分别表示指定的行和列(从 0 开始编号)。 7 | 8 | 你需要将每对 [ri, ci] 指定的行和列上的所有单元格的值加 1。 9 | 10 | 请你在执行完所有 indices 指定的增量操作后,返回矩阵中 「奇数值单元格」 的数目。 11 | 12 | 来源:力扣(LeetCode) 13 | 链接:https://leetcode-cn.com/problems/cells-with-odd-values-in-a-matrix 14 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 15 | """ 16 | 17 | 18 | class Solution: 19 | def oddCells(self, n: int, m: int, indices: list) -> int: 20 | # 模拟法 21 | Mat = [[0 for _ in range(m)] for _ in range(n)] 22 | for i, j in indices: 23 | Mat[i] = [1 + c for c in Mat[i]] 24 | for k in range(n): 25 | Mat[k][j] = Mat[k][j] + 1 26 | count = 0 27 | for row in Mat: 28 | for col in row: 29 | if col % 2 != 0: 30 | count += 1 31 | return count 32 | 33 | def oddCells2(self, n, m, indices): 34 | # 模拟+空间优化 35 | row = [0] * n 36 | col = [0] * m 37 | for i, j in indices: 38 | row[i] += 1 39 | col[j] += 1 40 | count = 0 41 | for i in range(n): 42 | for j in range(m): 43 | if (row[i] + col[j]) % 2 != 0: 44 | count += 1 45 | return count 46 | 47 | 48 | if __name__ == "__main__": 49 | s = Solution() 50 | print(s.oddCells2(2, 3, [[0, 1], [1, 1]])) 51 | -------------------------------------------------------------------------------- /05_leetcode/1276.!!方程_不浪费原料的汉堡制作方案.py: -------------------------------------------------------------------------------- 1 | """ 2 | 圣诞活动预热开始啦,汉堡店推出了全新的汉堡套餐。为了避免浪费原料,请你帮他们制定合适的制作计划。 3 | 4 | 给你两个整数 tomatoSlices 和 cheeseSlices,分别表示番茄片和奶酪片的数目。 5 | 不同汉堡的原料搭配如下: 6 | 7 | 巨无霸汉堡:4 片番茄和 1 片奶酪 8 | 小皇堡:2 片番茄和 1 片奶酪 9 | 请你以 [total_jumbo, total_small]([巨无霸汉堡总数,小皇堡总数])的格式返回恰当的制作方案, 10 | 使得剩下的番茄片 tomatoSlices 和奶酪片 cheeseSlices 的数量都是 0。 11 | 12 | 如果无法使剩下的番茄片 tomatoSlices 和奶酪片 cheeseSlices 的数量为 0,就请返回 []。 13 | 14 | 来源:力扣(LeetCode) 15 | 链接:https://leetcode-cn.com/problems/number-of-burgers-with-no-waste-of-ingredients 16 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 17 | """ 18 | class Solution: 19 | def numOfBurgers(self, tomatoSlices: int, cheeseSlices: int) ->list: 20 | # 超时 21 | ans = [] 22 | for b in range(cheeseSlices+1): 23 | s = cheeseSlices - b 24 | if 4*b + 2*s == tomatoSlices: 25 | ans = [b, s] 26 | break 27 | return ans 28 | 29 | def numOfBurgers2(self, tomatoSlices: int, cheeseSlices: int) ->list: 30 | # 44ms 55% 31 | b, m = divmod(tomatoSlices - 2*cheeseSlices, 2) 32 | if m == 0 and cheeseSlices >= b >= 0: 33 | return [b, cheeseSlices-b] 34 | else: 35 | return [] 36 | 37 | 38 | if __name__ == "__main__": 39 | t, c = 0, 0 40 | s = Solution() 41 | print(s.numOfBurgers2(t, c)) -------------------------------------------------------------------------------- /05_leetcode/1281.整数各位积和之差.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给你一个整数 n, 3 | 请你帮忙计算并返回该整数「各位数字之积」与「各位数字之和」的差。 4 | """ 5 | 6 | class Solution: 7 | def subtractProductAndSum(self, n: int) -> int: 8 | Sum, Product = 0, 1 9 | while n > 0: 10 | n, m = divmod(n, 10) 11 | Sum += m 12 | Product *= m 13 | return Product - Sum 14 | 15 | def subtractProductAndSum2(self, n): 16 | from functools import reduce #used in python3 17 | num=list(map(int, list(str(n)))) 18 | return reduce(lambda x,y:x*y,num)-sum(num) 19 | 20 | 21 | 22 | if __name__ == "__main__": 23 | s1 = Solution() 24 | while True: 25 | try: 26 | n = int(input()) 27 | print(s1.subtractProductAndSum(n)) 28 | except: 29 | break 30 | -------------------------------------------------------------------------------- /05_leetcode/1287.超过25%的元素.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给你一个非递减的 有序 整数数组, 3 | 已知这个数组中恰好有一个整数, 4 | 它的出现次数超过数组元素总数的 25%。 5 | """ 6 | 7 | class Solution: 8 | def findSpecialInteger(self, arr:list) -> int: 9 | target = len(arr) // 4 + 1 10 | i = 0 11 | count = 0 12 | while i < len(arr)-1: 13 | if arr[i] == arr[i+1]: 14 | count += 1 15 | else: 16 | count += 1 17 | if count >= target: 18 | return arr[i] 19 | else: 20 | count = 0 21 | i += 1 22 | else: 23 | return arr[i] 24 | 25 | if __name__ == "__main__": 26 | arr = [1,2,2,6,6,6,6,7,10] 27 | s1 = Solution() 28 | print(s1.findSpecialInteger(arr)) -------------------------------------------------------------------------------- /05_leetcode/1323.6和9组成的最大数.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给你一个仅由数字 6 和 9 组成的正整数 num。 3 | 4 | 你最多只能翻转一位数字,将 6 变成 9,或者把 9 变成 6 。 5 | 6 | 请返回你可以得到的最大数字。 7 | """ 8 | class Solution: 9 | def maximum69Number (self, num: int) -> int: 10 | num_list = list(str(num)) 11 | for index, num in enumerate(num_list): 12 | if num == '6': 13 | num_list[index] = '9' 14 | break 15 | 16 | return int(''.join(num_list)) 17 | 18 | def maximum69Number2(self, num:int): 19 | # 替换次数 20 | return int(str(num).replace('6', '9', 1)) 21 | 22 | 23 | if __name__ == '__main__': 24 | s1 = Solution() 25 | print(s1.maximum69Number(6669)) -------------------------------------------------------------------------------- /05_leetcode/1337.战斗力最弱的K行.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给你一个大小为 m * n 的方阵 mat,方阵由若干 军人 和 平民 组成,分别用 0 和 1 表示。 3 | 4 | 请你返回方阵中战斗力最弱的 k 行的索引,按从最弱到最强排序。 5 | 6 | 如果第 i 行的军人数量少于第 j 行,或者两行军人数量相同但 i 小于 j, 7 | 8 | 那么我们认为第 i 行的战斗力比第 j 行弱。 9 | 10 | 军人 总是 排在一行中的靠前位置,也就是说 1 总是出现在 0 之前。 11 | 12 | 来源:力扣(LeetCode) 13 | 链接:https://leetcode-cn.com/problems/the-k-weakest-rows-in-a-matrix 14 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 15 | """ 16 | 17 | 18 | class Solution: 19 | def kWeakestRows(self, mat: list, k: int) -> list: 20 | soilder_list = [row.count(1) for row in mat] 21 | rank = [i for i in range(len(mat))] 22 | rank.sort(key=lambda num: soilder_list[num]) 23 | return rank[:k] 24 | 25 | if __name__ == "__main__": 26 | mat = [[1, 1, 0, 0, 0], 27 | [1, 1, 1, 1, 0], 28 | [1, 0, 0, 0, 0], 29 | [1, 1, 0, 0, 0], 30 | [1, 1, 1, 1, 1]] 31 | k = 3 32 | s = Solution() 33 | print(s.kWeakestRows(mat, k)) -------------------------------------------------------------------------------- /05_leetcode/14.!最长公共前缀.py: -------------------------------------------------------------------------------- 1 | """ 2 | 编写一个函数来查找字符串数组中的最长公共前缀。 3 | 4 | 如果不存在公共前缀,返回空字符串 ""。 5 | """ 6 | from typing import List 7 | 8 | class Solution: 9 | def longestCommonPrefix(self, strs: List[str]) -> str: 10 | # 44ms 51% 11 | if len(strs) == 0: 12 | return "" 13 | length = 0 14 | pub = [] 15 | while length < len(strs[0]): 16 | pub.append(strs[0][length]) 17 | for word in strs[1:]: 18 | if length str: 27 | # 28ms 98% 28 | if len(strs) == 0: 29 | return '' 30 | s = strs[0] 31 | for i in range(1, len(strs)): 32 | while strs[i].find(s) != 0 : 33 | s = s[:-1] 34 | return s 35 | 36 | 37 | 38 | 39 | if __name__ == "__main__": 40 | s = Solution() 41 | print(s.longestCommonPrefix2(["flower","flow","flight"])) -------------------------------------------------------------------------------- /05_leetcode/167.两数之和-ii-输入有序数组.py: -------------------------------------------------------------------------------- 1 | # 2 | # @lc app=leetcode.cn id=167 lang=python3 3 | # 4 | # [167] 两数之和 II - 输入有序数组 5 | # 6 | from typing import List 7 | # @lc code=start 8 | class Solution: 9 | def twoSum(self, numbers: List[int], target: int) -> List[int]: 10 | ''' 11 | 99.17%, 5.25% 12 | [1,2,3,4,5,9] 11 13 | ''' 14 | left, right = 0, len(numbers)-1 15 | while left <= right: 16 | current = numbers[left] + numbers[right] 17 | if current > target: 18 | right -= 1 19 | elif current < target: 20 | left += 1 21 | else: 22 | return left+1, right+1 23 | 24 | 25 | # @lc code=end 26 | 27 | -------------------------------------------------------------------------------- /05_leetcode/168.Excel表列名称.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给定一个正整数,返回它在 Excel 表中相对应的列名称。 3 | 1 -> A 4 | 2 -> B 5 | 3 -> C 6 | ... 7 | 26 -> Z 8 | 27 -> AA 9 | 28 -> AB 10 | 11 | 15:17 -> 12 | """ 13 | 14 | class Solution: 15 | def convertToTitle(self, n: int) -> str: 16 | # 32ms 89.07% 辗转相除法 26进制 17 | start = ord('A') 18 | ans = [] 19 | while n > 0: 20 | n -= 1 # 关键 21 | n, t = divmod(n, 26) 22 | ans.append(chr(start + t)) 23 | 24 | return ''.join(ans[::-1]) 25 | 26 | 27 | if __name__ == "__main__": 28 | S = Solution() 29 | print(S.convertToTitle(27)) 30 | # print(S.convertToTitle(701)) 31 | # print(S.convertToTitle(52)) -------------------------------------------------------------------------------- /05_leetcode/171.Excel表列序号.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给定一个Excel表格中的列名称,返回其相应的列序号。 3 | """ 4 | 5 | class Solution: 6 | def titleToNumber(self, s: str) -> int: 7 | # 52ms 8 | count = 0 9 | for ch in s: 10 | count = count*26 + ord(ch) - 64 # ord('A') == 65 11 | return count 12 | 13 | 14 | 15 | if __name__ == "__main__": 16 | test = "AA" 17 | s = Solution() 18 | print(s.titleToNumber(test)) -------------------------------------------------------------------------------- /05_leetcode/178.Bigram.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给出第一个词 first 和第二个词 second, 3 | 4 | 考虑在某些文本 text 中可能以 "first second third" 形式出现的情况, 5 | 6 | 其中 second 紧随 first 出现,third 紧随 second 出现。 7 | 8 | 对于每种这样的情况,将第三个词 "third" 添加到答案中,并返回答案。 9 | 10 | 输入:text = "alice is a good girl she is a good student", first = "a", second = "good" 11 | 输出:["girl","student"] 12 | 13 | """ 14 | class Solution: 15 | def findOcurrences(self, text: str, first: str, second: str) -> list: 16 | third = [] 17 | text_list = text.split() 18 | if len(text_list) > 2: 19 | for index in range(len(text_list)-2): 20 | if text_list[index:index+2] == [first,second]: 21 | third.append(text_list[index+2]) 22 | return third 23 | 24 | def findOcurrences2(self, text: str, first: str, second: str) -> list: 25 | import re 26 | return re.findall(fr"(?<=\b{first} {second} )(\w+)", text) 27 | 28 | 29 | 30 | if __name__ == "__main__": 31 | s = Solution() 32 | text = "alice is a good girl she is a good student" 33 | first, second = "a", "good" 34 | print(s.findOcurrences(text, first, second)) -------------------------------------------------------------------------------- /05_leetcode/19.删除链表的倒数第-n-个结点.py: -------------------------------------------------------------------------------- 1 | # 2 | # @lc app=leetcode.cn id=19 lang=python3 3 | # 4 | # [19] 删除链表的倒数第 N 个结点 5 | # 6 | 7 | # Definition for singly-linked list. 8 | class ListNode: 9 | def __init__(self, val=0, next=None): 10 | self.val = val 11 | self.next = next 12 | # @lc code=start 13 | class Solution: 14 | def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: 15 | ''' 16 | 86.59% 13.34% 17 | ''' 18 | fake_head = ListNode(-1) 19 | fake_head.next = head 20 | 21 | slow = fast = fake_head 22 | for _ in range(n): 23 | fast = fast.next 24 | 25 | while fast.next is not None: 26 | fast = fast.next 27 | slow = slow.next 28 | delete = slow.next 29 | slow.next = delete.next 30 | del delete 31 | 32 | return fake_head.next 33 | 34 | # @lc code=end 35 | 36 | -------------------------------------------------------------------------------- /05_leetcode/198.打家劫舍.py: -------------------------------------------------------------------------------- 1 | # 2 | # @lc app=leetcode.cn id=198 lang=python3 3 | # 4 | # [198] 打家劫舍 5 | # 6 | 7 | # @lc code=start 8 | class Solution: 9 | def rob(self, nums: List[int]) -> int: 10 | # @lc code=end 11 | 12 | -------------------------------------------------------------------------------- /05_leetcode/20.有效的括号.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。 3 | 4 | 有效字符串需满足: 5 | 6 | 左括号必须用相同类型的右括号闭合。 7 | 左括号必须以正确的顺序闭合。 8 | 注意空字符串可被认为是有效字符串。 9 | """ 10 | class Solution: 11 | def isValid(self, s: str) -> bool: 12 | # 32ms 91.98% 13 | stack = [] 14 | ch_d = {'(':')', '[':']', '{':'}'} 15 | for ch in s: 16 | if ch in '([{': 17 | stack.append(ch) 18 | elif len(stack) > 0: 19 | if ch != ch_d[stack.pop()]: 20 | return False 21 | else: 22 | return False 23 | else: 24 | return len(stack) == 0 25 | 26 | 27 | if __name__ == "__main__": 28 | test = "()[]{}" 29 | S = Solution() 30 | print(S.isValid(test)) -------------------------------------------------------------------------------- /05_leetcode/21.合并两个有序链表.py: -------------------------------------------------------------------------------- 1 | """ 2 | 将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 3 | 4 | 输入:1->2->4, 1->3->4 5 | 输出:1->1->2->3->4->4 6 | """ 7 | 8 | # Definition for singly-linked list. 9 | class ListNode: 10 | def __init__(self, x): 11 | self.val = x 12 | self.next = None 13 | 14 | def __str__(self): 15 | res = [] 16 | ptr = self 17 | while ptr: 18 | res.append(ptr.val) 19 | ptr = ptr.next 20 | return res 21 | 22 | class Solution: 23 | def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: 24 | # 32ms 98.35% 25 | l3 = ListNode() 26 | p3 = l3 27 | while l1 and l2: 28 | if l1.val > l2.val: 29 | p3.next = l2 30 | l2 = l2.next 31 | else: 32 | p3.next = l1 33 | l1 = l1.next 34 | p3 = p3.next 35 | if l1 is not None: 36 | p3.next = l1 37 | elif l2 is not None: 38 | p3.next = l2 39 | return l3.next 40 | 41 | def mergeTwoLists2(self, l1, l2): 42 | # 递归且避免 长链逐个添加 43 | if l1 is None: 44 | return l2 45 | elif l2 is None: 46 | return l1 47 | elif l1.val < l2.val: 48 | l1.next = self.mergeTwoLists2(l1.next, l2) 49 | return l1 50 | else: 51 | l2.next = self.mergeTwoLists2(l1, l2.next) 52 | return l2 53 | 54 | 55 | 56 | 57 | if __name__ == "__main__": 58 | pass -------------------------------------------------------------------------------- /05_leetcode/215.数组中的第k个最大元素.py: -------------------------------------------------------------------------------- 1 | # 2 | # @lc app=leetcode.cn id=215 lang=python3 3 | # 4 | # [215] 数组中的第K个最大元素 5 | # 6 | 7 | # @lc code=start 8 | import heapq 9 | from typing import List 10 | class Solution: 11 | # 86.27% 12 | def findKthLargest(self, nums: List[int], k: int) -> int: 13 | heap = [-num for num in nums] 14 | heapq.heapify(heap) 15 | for i in range(k): 16 | result = heapq.heappop(heap) 17 | return -result 18 | 19 | 20 | 21 | if __name__ == "__main__": 22 | pass 23 | # @lc code=end -------------------------------------------------------------------------------- /05_leetcode/226.翻转二叉树.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 翻转一棵二叉树 3 | ''' 4 | 5 | # Definition for a binary tree node. 6 | class TreeNode: 7 | def __init__(self, x): 8 | self.val = x 9 | self.left = None 10 | self.right = None 11 | 12 | class Solution: 13 | def invertTree(self, root: TreeNode) -> TreeNode: 14 | if not isinstance(root, TreeNode): 15 | return None 16 | 17 | root.left, root.right = root.right, root.left 18 | if root.left: 19 | self.invertTree(root.left) 20 | if root.right: 21 | self.invertTree(root.right) 22 | return root 23 | 24 | -------------------------------------------------------------------------------- /05_leetcode/26.删除排序数组中的重复项.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给定一个排序数组,你需要在 原地 删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。 3 | 4 | 不要使用额外的数组空间,你必须在 原地 修改输入数组 并在使用 O(1) 额外空间的条件下完成。 5 | 6 | 来源:力扣(LeetCode) 7 | 链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array 8 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 9 | """ 10 | class Solution: 11 | def removeDuplicates(self, nums: list) -> int: 12 | # 44ms 91.34% 13 | nums_set = set(nums) 14 | nums.clear() 15 | nums.extend(list(nums_set)) 16 | nums.sort() 17 | return len(nums_set) 18 | 19 | def removeDuplicates2(self, nums): 20 | # 76ms 49% 21 | i = 0 22 | while i < len(nums): 23 | while i+1 < len(nums) and nums[i+1] == nums[i]: 24 | del nums[i+1] 25 | i += 1 26 | return len(nums) 27 | 28 | def removeDuplicates3(self, nums): 29 | # 60ms 66% 30 | # 倒着删除 31 | for i in range(len(nums))[::-1]: 32 | if i-1 != -1 and nums[i-1] == nums[i]: 33 | del nums[i] 34 | return len(nums) 35 | 36 | 37 | 38 | 39 | if __name__ == "__main__": 40 | nums = [0,0,1,1,1,2,2,3,3,4] 41 | s = Solution() 42 | print(s.removeDuplicates2(nums)) 43 | print(nums) -------------------------------------------------------------------------------- /05_leetcode/263.丑数.py: -------------------------------------------------------------------------------- 1 | """ 2 | 编写一个程序判断给定的数是否为丑数。 3 | 4 | 丑数就是只包含质因数 2, 3, 5 的正整数。 5 | """ 6 | 7 | 8 | class Solution: 9 | def isUgly(self, num: int) -> bool: 10 | # 44ms 51% 11 | if num <= 0: 12 | return False 13 | while num % 2 == 0: 14 | num = num // 2 15 | while num % 3 == 0: 16 | num = num // 3 17 | while num % 5 == 0: 18 | num = num // 5 19 | if num != 1: 20 | return False 21 | else: 22 | return True 23 | 24 | def isUgly2(self, num: int) -> bool: 25 | # 44ms 26 | if num <= 0: 27 | return False 28 | 29 | x = (2,3,5) 30 | while num!=1: 31 | for i in x: 32 | if num%i == 0: 33 | num //= i 34 | break 35 | else: 36 | return False 37 | return True 38 | 39 | def isUgly3(self, num): 40 | # 40ms 41 | if num <= 0: ## 如果num非正,就不是丑数 42 | return False 43 | while True: 44 | last = num 45 | if not num % 2: ## 如果2整除num,就除以2 46 | num >>= 1 47 | if not num % 3: ## 如果3整除num,就除以3 48 | num //= 3 49 | if not num % 5: ## 如果5整除num,就除以5 50 | num //= 5 51 | if num == 1: ## 如果若干次操作后,num变成1,说明num的因数只有2、3、5,是丑数 52 | return True 53 | if last == num: ## 如果1轮操作后,num没变,说明num不是丑数 54 | return False 55 | 56 | 57 | 58 | if __name__ == "__main__": 59 | s = Solution() 60 | print(s.isUgly(14)) 61 | 62 | -------------------------------------------------------------------------------- /05_leetcode/27.移除元素.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给你一个数组 nums 和一个值 val,你需要 原地 移除所有数值等于 val 的元素,并返回移除后数组的新长度。 3 | 4 | 不要使用额外的数组空间,你必须仅使用 O(1) 额外空间并 原地 修改输入数组。 5 | 6 | 元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。 7 | 8 | 来源:力扣(LeetCode) 9 | 链接:https://leetcode-cn.com/problems/remove-element 10 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 11 | """ 12 | from typing import List 13 | 14 | class Solution: 15 | def removeElement(self, nums: List[int], val: int) -> int: 16 | # 32ms 92.97% python特性解法 17 | for index in range(len(nums)-1,-1,-1): 18 | if nums[index] == val: 19 | del nums[index] 20 | return len(nums) 21 | 22 | def removeElement2(self, nums: List[int], val: int) -> int: 23 | # 题目想考察的 32ms 92.97% 24 | check, length = 0, -1 25 | while check < len(nums): 26 | if nums[check] == val: 27 | check += 1 28 | else: 29 | length += 1 30 | nums[length] = nums[check] 31 | check += 1 32 | return length+1 33 | 34 | 35 | if __name__ == "__main__": 36 | S = Solution() 37 | nums = [0,1,2,2,3,0,4,2] 38 | val = 2 39 | length = S.removeElement2(nums, val) 40 | print(nums[:length]) -------------------------------------------------------------------------------- /05_leetcode/278.第一个错误的版本.py: -------------------------------------------------------------------------------- 1 | # 2 | # @lc app=leetcode.cn id=278 lang=python3 3 | # 4 | # [278] 第一个错误的版本 5 | # 6 | def isBadVersion(num): 7 | if num >= 4: 8 | return True 9 | return False 10 | 11 | # @lc code=start 12 | # The isBadVersion API is already defined for you. 13 | # @param version, an integer 14 | # @return an integer 15 | # def isBadVersion(version): 16 | 17 | class Solution: 18 | def firstBadVersion(self, n): 19 | """ 20 | 找到最小的 bad 21 | :type n: int 22 | :rtype: int 23 | """ 24 | min_bad = n + 1 25 | start, end = 1, n 26 | while start <= end: 27 | mid = end + (start - end)//2 # 其他语言计算防止溢出 28 | # mid = (start + end)//2 29 | bad = isBadVersion(mid) 30 | if bad: 31 | min_bad = mid if min_bad > mid else min_bad 32 | end = mid - 1 33 | else: 34 | start = mid + 1 35 | 36 | return min_bad 37 | 38 | 39 | # @lc code=end 40 | 41 | if __name__ == "__main__": 42 | S = Solution() 43 | print(S.firstBadVersion(5)) 44 | 45 | -------------------------------------------------------------------------------- /05_leetcode/287.!!寻找重复数.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给定一个包含 n + 1 个整数的数组 nums, 3 | 其数字都在 1 到 n 之间(包括 1 和 n), 4 | 可知至少存在一个重复的整数。假设只有一个重复的整数,找出这个重复的数。 5 | 6 | 来源:力扣(LeetCode) 7 | 链接:https://leetcode-cn.com/problems/find-the-duplicate-number 8 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 9 | """ 10 | 11 | class Solution: 12 | def findDuplicate(self, nums: list) -> int: 13 | for i in range(len(nums)-1): 14 | for j in range(len(nums)-1,i,-1): 15 | if nums[i] == nums[j]: 16 | return nums[i] 17 | return 0 18 | 19 | def findDuplicate2(self, nums: list) -> int: 20 | # 二分法 21 | left, right = 1, len(nums)-1 22 | while left < right: 23 | mid = (left + right)//2 24 | count = 0 25 | for num in nums: 26 | # 统计小于mid的数字个数 27 | if num <= mid: 28 | count += 1 29 | if count > mid: 30 | # 例如小于4的数字有4个 31 | right = mid 32 | else: 33 | left = mid + 1 34 | return left 35 | 36 | def findDuplicate3(self, nums:list) -> int: 37 | # 快慢指针 38 | slow=0 39 | fast=0 40 | while(1): 41 | slow=nums[slow] 42 | fast=nums[nums[fast]] 43 | if(slow==fast): 44 | break 45 | find=0 46 | while(1): 47 | # slow进入圈子兜兜转转 48 | find=nums[find] 49 | slow=nums[slow] 50 | if(find==slow): 51 | return find 52 | 53 | 54 | 55 | 56 | 57 | 58 | if __name__ == "__main__": 59 | s1 = Solution() 60 | print(s1.findDuplicate3([1,3,4,2,2])) -------------------------------------------------------------------------------- /05_leetcode/290.单词规律.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给定一种规律 pattern 和一个字符串 str ,判断 str 是否遵循相同的规律。 3 | 4 | 这里的 遵循 指完全匹配,例如,  5 | pattern 里的每个字母和字符串 str 中的每个非空单词之间存在着 双向连接的对应规律。 6 | 7 | 来源:力扣(LeetCode) 8 | 链接:https://leetcode-cn.com/problems/word-pattern 9 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 10 | """ 11 | 12 | class Solution: 13 | def wordPattern(self, pattern: str, str: str) -> bool: 14 | # 32ms 88.48% 15 | str_sp = str.split(' ') 16 | if len(pattern) != len(str_sp): 17 | return False 18 | pattern_dict = {} 19 | for ch, word in zip(pattern, str_sp): 20 | if ch in pattern_dict: 21 | # 是否符合ch -> word映射 22 | if pattern_dict[ch] != word: 23 | return False 24 | elif word in pattern_dict.values(): 25 | # 已经有其他ch映射到word 26 | return False 27 | else: 28 | pattern_dict[ch] = word 29 | return True 30 | 31 | 32 | if __name__ == "__main__": 33 | S = Solution() 34 | pattern = "abba" 35 | st = "dog cat cat dig" 36 | print(S.wordPattern(pattern, st)) -------------------------------------------------------------------------------- /05_leetcode/3.无重复字符的最长子串.py: -------------------------------------------------------------------------------- 1 | # 2 | # @lc app=leetcode.cn id=3 lang=python3 3 | # 4 | # [3] 无重复字符的最长子串 5 | # 6 | """ 7 | 给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。 8 | 9 | 输入: "abcabcbb" 10 | 输出: 3 11 | 解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。 12 | 13 | """ 14 | # @lc code=start 15 | class Solution: 16 | def lengthOfLongestSubstring(self, s: str) -> int: 17 | ''' 18 | 90.54% 53.42% 19 | 滑动窗口(双指针) 滑窗内为不重复的子串,利用集合来判断是否重复 20 | ''' 21 | max_len = cur_len = 0 22 | left = right =0 23 | 24 | temp_set = set() 25 | while right < len(s): 26 | while left < right and s[right] in temp_set: 27 | temp_set.remove(s[left]) 28 | cur_len -=1 29 | left += 1 30 | temp_set.add(s[right]) 31 | cur_len += 1 32 | right += 1 33 | 34 | max_len = max(max_len, cur_len) 35 | 36 | return max_len 37 | 38 | # @lc code=end 39 | 40 | class Solution_old: 41 | def lengthOfLongestSubstring(self, s: str) -> int: 42 | # 滑动窗口 72ms 77.35% 43 | if len(s) == 0: 44 | return 0 45 | ans = f = 0 46 | for r in range(0, len(s)): 47 | if s[r] not in s[f:r]: 48 | ans = max(ans, r-f+1) 49 | else: 50 | while s[r] in s[f:r]: 51 | f += 1 52 | # print(s[f:r+1]) 53 | return ans 54 | 55 | 56 | if __name__ == "__main__": 57 | S = Solution() 58 | print(S.lengthOfLongestSubstring('')) 59 | 60 | -------------------------------------------------------------------------------- /05_leetcode/326.3的幂.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给定一个整数,写一个函数来判断它是否是 3 的幂次方。 3 | 4 | """ 5 | 6 | class Solution: 7 | def isPowerOfThree(self, n: int) -> bool: 8 | # 递归 76ms 98.96% 9 | return self.div3(n) 10 | 11 | def div3(self, n): 12 | if n == 1: 13 | return True 14 | elif n == 0: 15 | return False 16 | else: 17 | return n%3==0 and self.div3(n/3) 18 | 19 | def isPowerOfThree2(self, n): 20 | # 循环 96ms 61% 21 | while n not in (1, 0): 22 | n, m = divmod(n, 3) 23 | if m != 0: 24 | return False 25 | else: 26 | return True if n else False 27 | 28 | 29 | if __name__ == "__main__": 30 | S = Solution() 31 | print(S.isPowerOfThree2(9)) -------------------------------------------------------------------------------- /05_leetcode/344.反转字符串.py: -------------------------------------------------------------------------------- 1 | # 2 | # @lc app=leetcode.cn id=344 lang=python3 3 | # 4 | # [344] 反转字符串 5 | # 6 | 7 | from typing import List 8 | # @lc code=start 9 | class Solution: 10 | def reverseString(self, s: List[str]) -> None: 11 | """ 12 | 85.13 %, 6.71 % 13 | Do not return anything, modify s in-place instead. 14 | """ 15 | left, right = 0, len(s)-1 16 | while left < right: 17 | s[left], s[right] = s[right], s[left] 18 | left += 1 19 | right -= 1 20 | 21 | # s.reverse() # 97.56% 6.35% 22 | 23 | # @lc code=end 24 | 25 | -------------------------------------------------------------------------------- /05_leetcode/35.搜索插入位置.py: -------------------------------------------------------------------------------- 1 | # 2 | # @lc app=leetcode.cn id=35 lang=python3 3 | # 4 | # [35] 搜索插入位置 5 | # 6 | from typing import List 7 | 8 | # @lc code=start 9 | class Solution: 10 | def searchInsert(self, nums: List[int], target: int) -> int: 11 | insert_loc = len(nums) 12 | left, right = 0, insert_loc-1 13 | while left <= right: 14 | mid = left + (right - left) // 2 15 | temp = nums[mid] 16 | if temp >= target: 17 | insert_loc = min(insert_loc, mid) 18 | right = mid -1 19 | elif temp < target: 20 | left = mid + 1 21 | 22 | return insert_locs 23 | 24 | 25 | # @lc code=end 26 | 27 | class Solution_old: 28 | def searchInsert(self, nums: List[int], target: int) -> int: 29 | # 36ms 91.22% 30 | for index, num in enumerate(nums): 31 | if num < target: 32 | continue 33 | elif num > target: 34 | nums.insert(index, target) 35 | return index 36 | elif num == target: 37 | return index 38 | else: 39 | # 位置在最尾部 40 | nums.append(target) 41 | return len(nums)-1 42 | 43 | 44 | if __name__ == "__main__": 45 | test = [1,3,5,6] 46 | i = 5 47 | S = Solution() 48 | print(S.searchInsert(test, i)) -------------------------------------------------------------------------------- /05_leetcode/367.有效的完全平方数.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给定一个正整数 num,编写一个函数,如果 num 是一个完全平方数,则返回 True,否则返回 False。 3 | 4 | 说明:不要使用任何内置的库函数,如  sqrt。 5 | 6 | 来源:力扣(LeetCode) 7 | 链接:https://leetcode-cn.com/problems/valid-perfect-square 8 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 9 | """ 10 | 11 | class Solution: 12 | def isPerfectSquare(self, num: int) -> bool: 13 | # 36ms 80% 14 | if (num ** (1/2)).is_integer(): 15 | return True 16 | else: 17 | return False 18 | 19 | def isPerfectSquare2(self, num): 20 | # 52ms 27% 21 | i = 1 22 | while i*i 0: 31 | num -= i 32 | i += 2 33 | return num == 0 34 | 35 | 36 | if __name__ == "__main__": 37 | S = Solution() 38 | test = 16 39 | print(S.isPerfectSquare(test)) 40 | -------------------------------------------------------------------------------- /05_leetcode/461.汉明距离.py: -------------------------------------------------------------------------------- 1 | """ 2 | 两个整数之间的汉明距离指的是这两个数字对应二进制位不同的位置的数目。 3 | 4 | 给出两个整数 x 和 y,计算它们之间的汉明距离。 5 | """ 6 | class Solution: 7 | def hammingDistance(self, x: int, y: int) -> int: 8 | # 60ms 9 | temp = x ^ y # 异或 10 | bin_str = bin(temp) 11 | return bin_str.count('1') 12 | 13 | def hammingDistance2(self, x: int, y: int) -> int: 14 | # 44ms 15 | o = x ^ y # 异或 16 | count = 0 17 | while o != 0: 18 | o, mod = divmod(o, 2) 19 | if mod: 20 | count += 1 21 | return count 22 | 23 | def hammingDistance3(self, x: int, y: int) -> int: 24 | # 28ms 在取异或的过程中计算 25 | num = 0 26 | res = [] 27 | while x != 0 or y != 0: 28 | res.append((x%2, y%2)) 29 | x //= 2 30 | y //= 2 31 | for xii, yii in res: 32 | if xii != yii: 33 | num += 1 34 | return num 35 | 36 | 37 | if __name__ == "__main__": 38 | s = Solution() 39 | print(s.hammingDistance2(123, 234)) -------------------------------------------------------------------------------- /05_leetcode/474.一和零.py: -------------------------------------------------------------------------------- 1 | # 2 | # @lc app=leetcode.cn id=474 lang=python3 3 | # 4 | # [474] 一和零 5 | # 6 | from typing import List 7 | 8 | # @lc code=start 9 | class Solution: 10 | def findMaxForm(self, strs: List[str], m: int, n: int) -> int: 11 | ''' 12 | 暴力法 O(n^2) 13 | ''' 14 | # strs => (0count, 1count) 15 | for index, binstr in enumerate(strs): 16 | strs[index] = (binstr.count('0'), binstr.count('1')) 17 | 18 | max_subset_size = 0 19 | 20 | for left in range(len(strs)): 21 | cur_m, cur_n = 0, 0 22 | for right in range(left, len(strs)): 23 | cur_m += strs[right][0] 24 | cur_n += strs[right][1] 25 | if cur_m <= m and cur_n <=n: 26 | max_subset_size = max(max_subset_size, right-left+1) 27 | else: 28 | break 29 | 30 | return max_subset_size 31 | 32 | 33 | 34 | 35 | # @lc code=end 36 | 37 | if __name__ == "__main__": 38 | S = Solution() 39 | print(S.findMaxForm(["10", "0001", "111001", "1", "0"], m = 5, n = 3)) -------------------------------------------------------------------------------- /05_leetcode/476.数字的补数.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给定一个正整数,输出它的补数。补数是对该数的二进制表示取反。 3 | 4 | """ 5 | class Solution: 6 | def findComplement(self, num: int) -> int: 7 | # 48ms 23% 字符串方式处理 8 | num_str = bin(num) 9 | result = ['0','b'] 10 | for ch in num_str[2:]: 11 | if ch == '0': 12 | result.append('1') 13 | else: 14 | result.append('0') 15 | return int(''.join(result), 2) 16 | 17 | def findComplement2(self, num: int) -> int: 18 | # 40ms 48% 数学计算 num和补数相加 1111111 19 | return 2**(len(bin(num))-2)-num-1 20 | 21 | 22 | 23 | 24 | if __name__ == "__main__": 25 | s = Solution() 26 | print(s.findComplement3(5)) -------------------------------------------------------------------------------- /05_leetcode/485.最大连续1的个数.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给定一个二进制数组,计算其中最大连续1的个数 3 | """ 4 | 5 | class Solution: 6 | def findMaxConsecutiveOnes(self, nums: list) -> int: 7 | # 604ms 17.56% 8 | count, max_1 = 0, 0 9 | for num in nums: 10 | if num == 1: 11 | count += 1 12 | else: 13 | max_1 = max(count, max_1) 14 | count = 0 15 | return max(count, max_1) 16 | 17 | def findMaxConsecutiveOnes2(self, nums): 18 | # 532ms 30.57% 19 | zeros = [-1] 20 | zeros.extend([index for index,num in enumerate(nums) if num == 0]) 21 | zeros.append(len(nums)) 22 | return max([zeros[i+1] - zeros[i] -1 for i in range(len(zeros)-1)]) 23 | 24 | def findMaxConsecutiveOnes3(self, nums): 25 | # map, join 684ms 26 | return max(map(len, ''.join(map(str,nums)).split('0'))) 27 | 28 | 29 | if __name__ == "__main__": 30 | s = Solution() 31 | print(s.findMaxConsecutiveOnes3([0])) -------------------------------------------------------------------------------- /05_leetcode/50.leetcode.py: -------------------------------------------------------------------------------- 1 | # 50. Pow(x, n) 2 | 3 | class Solution: 4 | def myPow(self, x:float, n:int) -> float: 5 | return x**n -------------------------------------------------------------------------------- /05_leetcode/509.斐波那契数.py: -------------------------------------------------------------------------------- 1 | """ 2 | 斐波那契数,通常用 F(n) 表示,形成的序列称为斐波那契数列。 3 | 4 | 该数列由 0 和 1 开始,后面的每一项数字都是前面两项数字的和。也就是: 5 | 6 | F(0) = 0, F(1) = 1 7 | F(N) = F(N - 1) + F(N - 2), 其中 N > 1. 8 | 9 | 给定 N,计算 F(N)。 10 | """ 11 | 12 | class Solution: 13 | def fib(self, N: int) -> int: 14 | # "移步法" 15 | N_f, N_r = 1, 0 16 | if N == 0: 17 | return N_r 18 | elif N == 1: 19 | return N_f 20 | else: 21 | n = 1 22 | while n < N: 23 | N_f, N_r = (N_f + N_r), N_f 24 | n += 1 25 | return N_f 26 | 27 | 28 | if __name__ == "__main__": 29 | s = Solution() 30 | print(s.fib(4)) -------------------------------------------------------------------------------- /05_leetcode/520.检测大写字母.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给定一个单词,你需要判断单词的大写使用是否正确。 3 | 4 | 我们定义,在以下情况时,单词的大写用法是正确的: 5 | 6 | - 全部字母都是大写,比如"USA"。 7 | - 单词中所有字母都不是大写,比如"leetcode"。 8 | - 如果单词不只含有一个字母,只有首字母大写, 比如 "Google"。 9 | 10 | 否则,我们定义这个单词没有正确使用大写字母。 11 | """ 12 | 13 | class Solution: 14 | def detectCapitalUse(self, word: str) -> bool: 15 | # 36ms 85% 16 | if len(word) <= 1: 17 | return True 18 | firstB = True if word[0].isupper() else False 19 | secendB = True if word[1].isupper() else False 20 | if not firstB and secendB: 21 | return False 22 | 23 | for ch in word[2:]: 24 | if not firstB: 25 | # 首字母小写 26 | if ch.isupper(): 27 | return False 28 | elif secendB: 29 | # 第二个字母也大写 30 | 31 | if ch.islower(): 32 | return False 33 | else: 34 | # 第二个字母小写 35 | if ch.isupper(): 36 | return False 37 | else: 38 | return True 39 | 40 | 41 | 42 | if __name__ == "__main__": 43 | S = Solution() 44 | test = 'usA' 45 | print(S.detectCapitalUse(test)) -------------------------------------------------------------------------------- /05_leetcode/521.最长特殊序列I.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给定两个字符串,你需要从这两个字符串中找出 最长的特殊序列 。 3 | 4 | 最长特殊序列定义如下:该序列 为 某字符串独有 的 最长子序列 (即不能是其他字符串的子序列)。 5 | 6 | 子序列 可以通过 删去字符串中的某些 字符 实现,但不能改变剩余字符的 相对顺序。 7 | 8 | 空序列 为所有 字符串的子序列,任何字符串为其自身的子序列。 9 | 10 | 输入为两个字符串,输出最长特殊序列的长度。如果不存在,则返回 -1。 11 | 12 | """ 13 | class Solution: 14 | def findLUSlength(self, a: str, b: str) -> int: 15 | n, m = len(a), len(b) 16 | if n != m: 17 | return max(m, n) 18 | elif a == b: 19 | return -1 20 | else: 21 | return n 22 | 23 | 24 | 25 | if __name__ == "__main__": 26 | s = Solution() 27 | a = 'abcd' 28 | b = 'bcd' 29 | print(s.findLUSlength(a, b)) -------------------------------------------------------------------------------- /05_leetcode/53.最大子序和.py: -------------------------------------------------------------------------------- 1 | #! -*- encoding:utf-8 -*- 2 | """ 3 | @File : 53.最大子序和.py 4 | @Author : Zachary Li 5 | @Contact : li_zaaachary@163.com 6 | @Dscpt : 7 | """ 8 | # 9 | # @lc app=leetcode.cn id=53 lang=python3 10 | # 11 | # [53] 最大子序和 12 | # 13 | from typing import List 14 | 15 | # @lc code=start 16 | class Solution: 17 | def maxSubArray_org(self, nums: List[int]) -> int: 18 | ''' 19 | 76.21 % 20 | 思路 21 | 滑窗遍历列表; 22 | sum < 0 时候 left+1 直到 与right重合; 23 | right + 1,重新计算 current 值; 24 | ''' 25 | if len(nums) == 0: 26 | return 27 | left = 0 28 | current, maxsum = 0, nums[0] 29 | for right in range(len(nums)): 30 | current += nums[right] 31 | maxsum = max(maxsum, current) 32 | while current <= 0 and left <= right: 33 | current -= nums[left] 34 | left += 1 35 | return maxsum 36 | 37 | def maxSubArray(self, nums: List[int]) -> int: 38 | ''' 39 | 76.21% 40 | 作者:z1m 41 | 动态规划,原地修改数组 42 | ''' 43 | maxnum = nums[0] 44 | for i in range(1,len(nums)): 45 | if nums[i - 1] > 0: 46 | nums[i] += nums[i - 1] 47 | maxnum = max(maxnum,nums[i]) 48 | return maxnum 49 | 50 | # @lc code=end 51 | 52 | 53 | if __name__ == "__main__": 54 | S = Solution() 55 | print(S.maxSubArray([-2,1,-3,4,-1,2,1,-5,4])) -------------------------------------------------------------------------------- /05_leetcode/541.反转字符串II.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给定一个字符串 s 和一个整数 k,你需要对从字符串开头算起的每隔 2k 个字符的前 k 个字符进行反转。 3 | 4 | - 如果剩余字符少于 k 个,则将剩余字符全部反转。 5 | - 如果剩余字符小于 2k 但大于或等于 k 个,则反转前 k 个字符,其余字符保持原样。 6 | 7 | """ 8 | 9 | class Solution: 10 | def reverseStr(self, s: str, k: int) -> str: 11 | s_list = list(s) 12 | for index in range(0, len(s), 2*k): 13 | s_list[index:index+k] = reversed(s_list[index:index+k]) 14 | return ''.join(s_list) 15 | 16 | 17 | if __name__ == "__main__": 18 | S = Solution() 19 | print(S.reverseStr("abcdefg", 2)) -------------------------------------------------------------------------------- /05_leetcode/55.!!贪心_跳跃游戏.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给定一个非负整数数组,你最初位于数组的第一个位置。 3 | 4 | 数组中的每个元素代表你在该位置可以跳跃的最大长度。 5 | 6 | 判断你是否能够到达最后一个位置。 7 | """ 8 | class Solution: 9 | def canJump(self, nums: list) -> bool: 10 | # DFS 超时 11 | self.visited = [False] * len(nums) 12 | self.nums = nums 13 | return self.DFS(0) 14 | 15 | def DFS(self, start): 16 | self.visited[start] = True 17 | if start == len(self.nums) - 1: 18 | return True 19 | Neighbor = [start + i for i in range(1, self.nums[start] + 1) if 0 <= start + i < len(self.nums)] 20 | Neighbor.extend([start - i for i in range(1, self.nums[start] + 1) if 0 <= start - i < len(self.nums)]) 21 | for nb in Neighbor: 22 | if not self.visited[nb]: 23 | if self.DFS(nb): 24 | return True 25 | else: 26 | self.visited[start] = False 27 | return False 28 | 29 | def canJump2(self, nums:list) -> bool: 30 | """ 31 | 思路:尽可能到达最远位置(贪心)。 如果能到达某个位置,那一定能到达它前面的所有位置。 32 | 方法:初始化最远位置为0,然后遍历数组,如果当前位置能到达, 33 | 并且当前位置+跳数>最远位置,就更新最远位置。最后比较最远位置和数组长度。 34 | 复杂度:时间复杂度O(n),空间复杂度O(1)。 35 | 作者:mo-lan-4 36 | """ 37 | max_jump = 0 # 当前能到达的最远处 38 | for i, jump in enumerate(nums): 39 | if max_jump >= i and i + jump > max_jump: 40 | # 如果当前位置是到达的,且当前位置可跳到更远的位置 41 | max_jump = i + jump 42 | return max_jump >= i 43 | 44 | 45 | if __name__ == "__main__": 46 | test = [2, 3, 1, 1, 4] 47 | s = Solution() 48 | print(s.canJump2(test)) -------------------------------------------------------------------------------- /05_leetcode/557.反转字符串中的单词-iii.py: -------------------------------------------------------------------------------- 1 | # 2 | # @lc app=leetcode.cn id=557 lang=python3 3 | # 4 | # [557] 反转字符串中的单词 III 5 | # 6 | 7 | # @lc code=start 8 | class Solution: 9 | def reverseWords(self, s: str) -> str: 10 | ''' 11 | 使用堆栈 15.95% 8.21% 12 | "Let's take LeetCode contest" 13 | "s'teL ekat edoCteeL tsetnoc" 14 | ''' 15 | result = [' '] * len(s) 16 | stack = [] 17 | end = len(s) - 1 18 | while end >= 0: 19 | if s[end] != ' ': 20 | stack.append(s[end]) 21 | end -= 1 22 | else: 23 | result[end+1:end+1+len(stack)] = stack 24 | stack.clear() 25 | end -= 1 26 | else: 27 | if len(stack) > 0: 28 | result[:len(stack)] = stack 29 | 30 | return ''.join(result) 31 | 32 | 33 | 34 | # @lc code=end 35 | 36 | class Solution_py: 37 | def reverseWords(self, s: str) -> str: 38 | ''' 39 | 76.55% 82.21% 40 | ''' 41 | s_list = s.split(' ') 42 | for index, string in enumerate(s_list): 43 | s_list[index] = ''.join(list(reversed(string))) 44 | return ' '.join(s_list) 45 | 46 | 47 | if __name__ == "__main__": 48 | S = Solution() 49 | print(S.reverseWords('just have a test')) -------------------------------------------------------------------------------- /05_leetcode/560.!!前缀和_和为K的子数组.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给定一个整数数组和一个整数 k,你需要找到该数组中和为 k 的连续的子数组的个数。 3 | 4 | 输入:nums = [1,1,1], k = 2 5 | 输出: 2 , [1,1] 与 [1,1] 为两种不同的情况。 6 | """ 7 | from typing import List 8 | 9 | class Solution: 10 | def subarraySum(self, nums: List[int], k: int) -> int: 11 | # 暴力法 超时 12 | current, ans = 0, 0 13 | for index in range(len(nums)): 14 | current = 0 15 | for num in nums[index::]: 16 | current += num 17 | if current == k: 18 | ans += 1 19 | return ans 20 | 21 | 22 | def subarraySum2(self, nums: List[int], k: int) -> int: 23 | # 72ms 96% 前缀和 + 字典 24 | if len(nums) == 0: 25 | return 0 26 | prev_dict = {0 : 1} 27 | prev_sum, ans = 0, 0 28 | for num in nums: 29 | prev_sum += num 30 | if prev_dict.get(prev_sum-k): 31 | ans += prev_dict[prev_sum-k] 32 | prev_dict[prev_sum] = prev_dict.get(prev_sum, 0) + 1 33 | return ans 34 | 35 | 36 | if __name__ == "__main__": 37 | S = Solution() 38 | print(S.subarraySum2([1,1,1], 2)) -------------------------------------------------------------------------------- /05_leetcode/561.数组拆分I.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给定长度为 2n 的数组, 你的任务是将这些数分成 n 对, 3 | 例如 (a1, b1), (a2, b2), ..., (an, bn) , 4 | 使得从1 到 n 的 min(ai, bi) 总和最大。 5 | 6 | 来源:力扣(LeetCode) 7 | 链接:https://leetcode-cn.com/problems/array-partition-i 8 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 9 | """ 10 | 11 | class Solution: 12 | def arrayPairSum(self, nums: list) -> int: 13 | # 376ms 43.66% 排序后求偶数位和 14 | nums.sort() 15 | return sum(nums[::2]) 16 | 17 | if __name__ == "__main__": 18 | test = [1,4,3,2] 19 | s = Solution() 20 | print(s.arrayPairSum(test)) -------------------------------------------------------------------------------- /05_leetcode/567.字符串的排列.py: -------------------------------------------------------------------------------- 1 | # 2 | # @lc app=leetcode.cn id=567 lang=python3 3 | # 4 | 5 | # https://leetcode-cn.com/problems/permutation-in-string/solution/zi-fu-chuan-de-pai-lie-by-leetcode-solut-7k7u/ 6 | # [567] 字符串的排列 7 | # 8 | 9 | # @lc code=start 10 | from collections import Counter 11 | class Solution: 12 | def checkInclusion(self, s1: str, s2: str) -> bool: 13 | ''' 14 | 滑窗#1 21.38% 5.85% 15 | ''' 16 | if len(s1) > len(s2): 17 | return False 18 | count_dict = Counter(s1) 19 | 20 | left = 0 21 | while left <= len(s2) - len(s1): 22 | count_dict2 = Counter(s2[left:left+len(s1)]) 23 | for key in count_dict.keys(): 24 | if count_dict[key] != count_dict2[key]: 25 | break 26 | else: 27 | # 无 break 正常运行,说明匹配 28 | return True 29 | left += 1 30 | else: 31 | return False 32 | 33 | 34 | 35 | 36 | # @lc code=end 37 | 38 | if __name__ == "__main__": 39 | S = Solution() 40 | print(S.checkInclusion('ab', 'eidbaoo')) -------------------------------------------------------------------------------- /05_leetcode/572.另一个树的子树.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | 给定两个非空二叉树 s 和 t,检验 s 中是否包含和 t 具有相同结构和节点值的子树。 4 | s 的一个子树包括 s 的一个节点和这个节点的所有子孙。s 也可以看做它自身的一棵子树。 5 | 6 | """ 7 | 8 | # Definition for a binary tree node. 9 | class TreeNode: 10 | def __init__(self, val=0, left=None, right=None): 11 | self.val = val 12 | self.left = left 13 | self.right = right 14 | 15 | 16 | class Solution: 17 | def isSubtree(self, s: TreeNode, t: TreeNode) -> bool: 18 | pass 19 | 20 | def areSame(self, T1, T2): 21 | if T1 is None and T2 is None: 22 | return True 23 | elif not (T1 and T2): 24 | return False 25 | elif T1.val != T2.val: 26 | return False 27 | else: 28 | return self.areSame(T1.left, T2.right) and self.areSame(T1.right, T2.right) 29 | 30 | 31 | if __name__ == "__main__": 32 | pass -------------------------------------------------------------------------------- /05_leetcode/575.分糖果.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给定一个偶数长度的数组,其中不同的数字代表着不同种类的糖果,每一个数字代表一个糖果。 3 | 你需要把这些糖果平均分给一个弟弟和一个妹妹。 4 | 返回妹妹可以获得的最大糖果的种类数。 5 | 6 | 来源:力扣(LeetCode) 7 | 链接:https://leetcode-cn.com/problems/distribute-candies 8 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 9 | """ 10 | 11 | class Solution: 12 | def distributeCandies(self, candies: list) -> int: 13 | total = len(candies) 14 | candy_set = set(candies) 15 | candy_type = len(candy_set) 16 | half = total // 2 17 | return min(half, candy_type) 18 | 19 | if __name__ == "__main__": 20 | pass -------------------------------------------------------------------------------- /05_leetcode/617.合并二叉树.py: -------------------------------------------------------------------------------- 1 | # 2 | # @lc app=leetcode.cn id=617 lang=python3 3 | # 4 | # [617] 合并二叉树 5 | # 6 | 7 | # @lc code=start 8 | # Definition for a binary tree node. 9 | # class TreeNode: 10 | # def __init__(self, val=0, left=None, right=None): 11 | # self.val = val 12 | # self.left = left 13 | # self.right = right 14 | class Solution: 15 | 16 | def mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode: 17 | # 99.88% 5.01% 18 | if root1 and root2: 19 | root1.val += root2.val 20 | root1.left = self.mergeTrees(root1.left, root2.left) 21 | root1.right = self.mergeTrees(root1.right, root2.right) 22 | return root1 23 | elif root1: 24 | return root1 25 | elif root2: 26 | return root2 27 | # @lc code=end 28 | 29 | # def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode: 30 | # if not t1: 31 | # return t2 32 | # if not t2: 33 | # return t1 34 | 35 | # merged = TreeNode(t1.val + t2.val) 36 | # merged.left = self.mergeTrees(t1.left, t2.left) 37 | # merged.right = self.mergeTrees(t1.right, t2.right) 38 | # return merged -------------------------------------------------------------------------------- /05_leetcode/628.三个数的最大乘积.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给定一个整型数组,在数组中找出由三个数组成的最大乘积,并输出这个乘积。 3 | 4 | """ 5 | class Solution: 6 | def maximumProduct(self, nums: list) -> int: 7 | # 392ms 33.44% 8 | # 找到最大的3个和最小的四个数后暴力枚举 9 | from itertools import permutations as pr 10 | max_three, min_four = [], [] 11 | target = [] 12 | if len(nums) > 7: 13 | for num in nums: 14 | max_three.append(num) 15 | min_four.append(num) 16 | max_three.sort(reverse=True) 17 | min_four.sort() 18 | if len(max_three) > 3: 19 | max_three.pop() 20 | if len(min_four) > 4: 21 | min_four.pop() 22 | target.extend(max_three) 23 | target.extend(min_four) 24 | else: 25 | target = nums 26 | 27 | print(target) 28 | ans_max = target[0] * target[1] * target[2] 29 | for couple in pr(target, 3): 30 | # print(couple) 31 | temp = couple[0]*couple[1]*couple[2] 32 | ans_max = max(temp, ans_max) 33 | return ans_max 34 | 35 | def maximumProduct2(self, nums): 36 | # 324ms 66% 37 | # 排序后考虑3大 2大1小 38 | nums.sort() 39 | return max(nums[-1]*nums[-2]*nums[-3],nums[-1]*nums[0]*nums[1]) 40 | 41 | 42 | if __name__ == "__main__": 43 | test = [1,2,-3,4] 44 | s= Solution() 45 | print(s.maximumProduct(test)) -------------------------------------------------------------------------------- /05_leetcode/645.错误的集合.py: -------------------------------------------------------------------------------- 1 | """ 2 | 集合 S 包含从1到 n 的整数。 3 | 不幸的是,因为数据错误,导致集合里面某一个元素复制了成了集合里面的另外一个元素的值, 4 | 导致集合丢失了一个整数并且有一个元素重复。 5 | 6 | 给定一个数组 nums 代表了集合 S 发生错误后的结果。 7 | 你的任务是首先寻找到重复出现的整数,再找到丢失的整数,将它们以数组的形式返回。 8 | 9 | 来源:力扣(LeetCode) 10 | 链接:https://leetcode-cn.com/problems/set-mismatch 11 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 12 | """ 13 | from typing import List 14 | 15 | class Solution: 16 | def findErrorNums(self, nums: List[int]) -> List[int]: 17 | # 288ms 39% 使用数组标记每个数字是否访问到 18 | flag = [False]*len(nums) 19 | ans = [0, 0] 20 | for num in nums: 21 | if flag[num-1]: 22 | ans[0] = num 23 | else: 24 | flag[num-1] = True 25 | ans[1] = flag.index(False)+1 26 | return ans 27 | 28 | 29 | 30 | 31 | if __name__ == "__main__": 32 | S = Solution() 33 | nums = [1,2,2,4] 34 | print(S.findErrorNums(nums)) -------------------------------------------------------------------------------- /05_leetcode/657.机器人能否返回原点.py: -------------------------------------------------------------------------------- 1 | """ 2 | 在二维平面上,有一个机器人从原点 (0, 0) 开始。 3 | 给出它的移动顺序,判断这个机器人在完成移动后是否在 (0, 0) 处结束。 4 | 5 | 移动顺序由字符串表示。字符 move[i] 表示其第 i 次移动。 6 | 机器人的有效动作有 R(右),L(左),U(上)和 D(下)。 7 | 如果机器人在完成所有动作后返回原点,则返回 true。否则,返回 false。 8 | 9 | 注意:机器人“面朝”的方向无关紧要。 10 | “R” 将始终使机器人向右移动一次, 11 | “L” 将始终向左移动等。 12 | 此外,假设每次移动机器人的移动幅度相同。 13 | 14 | 来源:力扣(LeetCode) 15 | 链接:https://leetcode-cn.com/problems/robot-return-to-origin 16 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 17 | """ 18 | 19 | class Solution: 20 | def judgeCircle(self, moves: str) -> bool: 21 | # 80ms 22 | hori, vert = 0, 0 23 | for dirction in moves: 24 | if dirction == 'U': 25 | vert += 1 26 | elif dirction == 'D': 27 | vert -= 1 28 | elif dirction == 'L': 29 | hori += 1 30 | else: 31 | hori -= 1 32 | 33 | if hori or vert: 34 | return False 35 | else: 36 | return True 37 | 38 | def judgeCircle2(self, moves: str) -> bool: 39 | # 52ms 40 | return moves.count('U')==moves.count('D') and moves.count('R')==moves.count('L') 41 | 42 | 43 | if __name__ == "__main__": 44 | test = "UD" 45 | s = Solution() 46 | print(s.judgeCircle(test)) -------------------------------------------------------------------------------- /05_leetcode/680.!验证回文字符串II.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给定一个非空字符串 s,最多删除一个字符。判断是否能成为回文字符串。 3 | """ 4 | class Solution: 5 | def validPalindrome(self, s: str) -> bool: 6 | # 200ms 26% 7 | front, rear = 0, len(s)-1 8 | if rear <= 1: 9 | # 长度小于等于2的字符串满足 10 | return True 11 | 12 | def notmatch(front, rear): 13 | while front < rear: 14 | # 找到发生不匹配的位置 15 | if s[front] == s[rear]: 16 | front += 1 17 | rear -= 1 18 | else: 19 | return (front, rear) 20 | else: 21 | return False 22 | 23 | result = notmatch(front, rear) 24 | if not result: 25 | return True 26 | else: 27 | front, rear = result 28 | return (not notmatch(front+1, rear)) or (not notmatch(front, rear-1)) 29 | 30 | def validPalindrome2(self, s): 31 | # 128ms 57.71 更好的写法 32 | isPalindrome = lambda s: s == s[::-1] 33 | strPart = lambda s, x: s[:x] + s[x + 1:] 34 | left = 0 35 | right = len(s) - 1 36 | while left < right: 37 | if s[left] != s[right]: 38 | return isPalindrome(strPart(s, left)) or isPalindrome(strPart(s, right)) 39 | left += 1 40 | right -= 1 41 | return True 42 | 43 | 44 | if __name__ == "__main__": 45 | test = "abca" 46 | S = Solution() 47 | print(S.validPalindrome(test)) -------------------------------------------------------------------------------- /05_leetcode/69.x的平方根.py: -------------------------------------------------------------------------------- 1 | """ 2 | 实现 int sqrt(int x)函数 3 | 计算并返回x的平方根,其中x是非负整数。 4 | 由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。 5 | """ 6 | 7 | class Solution: 8 | def mySqrt(self, x: int) -> int: 9 | # 超时 应该换二分法 10 | half = x//2 11 | for i in range(1, half+1): 12 | if i ** 2 <= x < (i+1)**2: 13 | return i 14 | else: 15 | return x 16 | 17 | def mySqrt2(self, x): 18 | # 44ms 80% 19 | return int(x**(1/2)) 20 | 21 | def mySqrt3(self, x): 22 | # 60ms 32% 二分法 23 | start, end = 0, x 24 | while start <= end: 25 | mid = (start + end) // 2 26 | square = mid **2 27 | if square <= x <(mid+1)**2: 28 | return mid 29 | elif square > x: 30 | end = mid -1 31 | else: 32 | start = mid + 1 33 | 34 | 35 | if __name__ == "__main__": 36 | S = Solution() 37 | for i in range(0, 38): 38 | print(S.mySqrt3(i)) -------------------------------------------------------------------------------- /05_leetcode/7.!位_整数反转.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。 3 | 4 | 假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。 5 | 请根据这个假设,如果反转后整数溢出那么就返回 0。 6 | """ 7 | class Solution: 8 | def reverse(self, x: int) -> int: 9 | # 52ms 字符串 10 | if x > 0: 11 | x_str = str(x) 12 | else: 13 | x_str = str(-x) + '-' 14 | ans = int(''.join(reversed(x_str))) 15 | 16 | if ans >= 2147483647 or ans <= -2147483648: 17 | # if ans >= (1 << 31) -1 or ans <= -1<<31: 18 | return 0 19 | else: 20 | return ans 21 | 22 | def reverse2(self, x): 23 | # 36ms 83.22% 24 | y, res = abs(x), 0 25 | # 则其数值范围为 [−2^31, 2^31 − 1] 根据正负来选择边界 26 | boundry = (1<<31) -1 if x > 0 else 1 << 31 27 | while y != 0: 28 | # 结果*10 加上y的末尾 29 | res = res*10 + y%10 30 | if res > boundry : 31 | return 0 32 | y //=10 33 | return res if x >0 else -res 34 | 35 | 36 | if __name__ == "__main__": 37 | s = Solution() 38 | print(s.reverse(1534236469)) 39 | print(s.reverse2(-2147483412)) 40 | 41 | -------------------------------------------------------------------------------- /05_leetcode/70.爬楼梯.py: -------------------------------------------------------------------------------- 1 | #! -*- encoding:utf-8 -*- 2 | """ 3 | @File : 70.爬楼梯.py 4 | @Author : Zachary Li 5 | @Contact : li_zaaachary@163.com 6 | @Dscpt : Leetcode 7 | """ 8 | # 9 | # @lc app=leetcode.cn id=70 lang=python3 10 | # 11 | # [70] 爬楼梯 12 | # 13 | 14 | # @lc code=start 15 | class Solution: 16 | def climbStairs(self, n: int) -> int: 17 | ''' 18 | 思路:f(n) = f(n-1) + f(n-2) 19 | 结果:36ms; 84.34%; 7.25% 20 | ''' 21 | if n <= 2: 22 | return n 23 | 24 | n_1, n_2 = 1, 2 25 | for _ in range(3, n+1): 26 | n_1, n_2 = n_2, n_1 + n_2 27 | return n_2 28 | 29 | # @lc code=end 30 | 31 | if __name__ == "__main__": 32 | S = Solution() 33 | print(S.climbStairs(4)) -------------------------------------------------------------------------------- /05_leetcode/704.二分查找.py: -------------------------------------------------------------------------------- 1 | # 2 | # @lc app=leetcode.cn id=704 lang=python3 3 | # 4 | # [704] 二分查找 5 | # 6 | from typing import List 7 | 8 | # @lc code=start 9 | class Solution: 10 | def search(self, nums: List[int], target: int) -> int: 11 | left, right = 0, len(nums)-1 12 | while left <= right: 13 | mid = (left + right) // 2 14 | temp = nums[mid] 15 | if temp == target: 16 | return mid 17 | elif temp > target: 18 | right = mid-1 19 | else: 20 | left = mid+1 21 | else: 22 | return -1 23 | 24 | # @lc code=end 25 | 26 | if __name__ == "__main__": 27 | S = Solution() 28 | print(S.search([-1,0,3,5,9,12], 2)) 29 | print(S.search([-1,0,3,5,9,12], 9)) 30 | print(S.search([-1,0,3,5,9,12], 0)) 31 | -------------------------------------------------------------------------------- /05_leetcode/771.宝石与石头.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给定字符串J 代表石头中 宝石 的类型,和字符串 S代表你拥有的石头。  3 | 4 | S 中每个字符代表了一种你拥有的石头的类型,你想知道你拥有的 石头 中有多少是 宝石。 5 | 6 | J 中的字母不重复,J 和 S中的所有字符都是字母。字母区分大小写,因此"a"和"A"是不同类型的石头 7 | 8 | 来源:力扣(LeetCode) 9 | 链接:https://leetcode-cn.com/problems/jewels-and-stones 10 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 11 | """ 12 | 13 | class Solution: 14 | def numJewelsInStones(self, J: str, S: str) -> int: 15 | count = 0 16 | for stone in S: 17 | if stone in J: 18 | count += 1 19 | return count 20 | 21 | def numJewelsInStones2(self, J: str, S: str) -> int: 22 | return len([ch for ch in S if ch in J]) 23 | 24 | 25 | if __name__ == '__main__': 26 | J = "aA" 27 | S = "aAAbbbb" 28 | s1 = Solution() 29 | print(s1.numJewelsInStones2(J, S)) -------------------------------------------------------------------------------- /05_leetcode/804.摩尔斯密码词.py: -------------------------------------------------------------------------------- 1 | """ 2 | 国际摩尔斯密码定义一种标准编码方式,将每个字母对应于一个由一系列点和短线组成的字符串,  3 | 比如: "a" 对应 ".-", "b" 对应 "-...", "c" 对应 "-.-.", 等等。 4 | 5 | 为了方便,所有26个英文字母对应摩尔斯密码表如下: 6 | [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] 7 | 8 | 给定一个单词列表,每个单词可以写成每个字母对应摩尔斯密码的组合。 9 | 例如,"cab" 可以写成 "-.-..--...",(即 "-.-." + "-..." + ".-"字符串的结合)。 10 | 11 | 我们将这样一个连接过程称作单词翻译。返回我们可以获得所有词不同单词翻译的数量。 12 | 13 | 来源:力扣(LeetCode) 14 | 链接:https://leetcode-cn.com/problems/unique-morse-code-words 15 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 16 | """ 17 | trans = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] 18 | 19 | class Solution: 20 | def uniqueMorseRepresentations(self, words: list) -> int: 21 | # 52ms 22 | global trans 23 | code_set = set() 24 | for word in words: 25 | code = [] 26 | for ch in word: 27 | code.append(trans[ord(ch) - 97]) 28 | code_set.add(''.join(code)) 29 | return len(code_set) 30 | 31 | def uniqueMorseRepresentations2(self, word): 32 | # 44ms 33 | global trans 34 | seen = {"".join(trans[ord(c) - ord('a')] for c in word) 35 | for word in words} # 集合生成式 36 | return len(seen) 37 | 38 | 39 | if __name__ == "__main__": 40 | s = Solution() 41 | words = ["gin", "zen", "gig", "msg"] 42 | print(s.uniqueMorseRepresentations(words)) -------------------------------------------------------------------------------- /05_leetcode/811.子域名访问计数.py: -------------------------------------------------------------------------------- 1 | """ 2 | 一个网站域名,如"discuss.leetcode.com",包含了多个子域名。 3 | 4 | 作为顶级域名,常用的有"com",下一级则有"leetcode.com",最低的一级为"discuss.leetcode.com"。 5 | 6 | 当我们访问域名"discuss.leetcode.com"时,也同时访问了其父域名"leetcode.com"以及顶级域名 "com"。 7 | 8 | 给定一个带访问次数和域名的组合,要求分别计算每个域名被访问的次数。 9 | 10 | 其格式为访问次数+空格+地址,例如:"9001 discuss.leetcode.com"。 11 | 12 | 接下来会给出一组访问次数和域名组合的列表cpdomains 。 13 | 14 | 要求解析出所有域名的访问次数,输出格式和输入格式相同,不限定先后顺序。 15 | """ 16 | 17 | 18 | 19 | class Solution: 20 | def subdomainVisits(self, cpdomains: list) -> list: 21 | result = [] 22 | visit_dict = {} 23 | for cp in cpdomains: 24 | num, domains = cp.split(' ') 25 | domain_list = domains.split('.') 26 | for i in range(len(domain_list)): 27 | temp = '.'.join(domain_list[-i:]) 28 | visit_dict[temp] = visit_dict.get(temp, 0) + int(num) 29 | for domain, num in visit_dict.items(): 30 | result.append(str(num)+' '+domain) 31 | return result 32 | 33 | def subdomainVisits2(self, cpdomains: list) -> list: 34 | import collections 35 | ans = collections.Counter() 36 | for cp in cpdomains: 37 | num, domains = cp.split(' ') 38 | domain_list = domains.split('.') 39 | for i in range(len(domain_list)): 40 | temp = '.'.join(domain_list[-i:]) 41 | ans[temp] += int(num) 42 | return [["{} {}".format(ct, dom) for dom, ct in ans.items()]] 43 | 44 | if __name__ == "__main__": 45 | test = ["900 google.mail.com", "50 yahoo.com", "1 intel.mail.com", "5 wiki.org"] 46 | s = Solution() 47 | print(s.subdomainVisits(test)) -------------------------------------------------------------------------------- /05_leetcode/819.最常见的词.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给定一个段落 (paragraph) 和一个禁用单词列表 (banned)。 3 | 返回出现次数最多,同时不在禁用列表中的单词。 4 | 题目保证至少有一个词不在禁用列表中,而且答案唯一。 5 | 6 | 禁用列表中的单词用小写字母表示,不含标点符号。段落中的单词不区分大小写。答案都是小写字母。 7 | 8 | """ 9 | import re 10 | from typing import List 11 | 12 | class Solution: 13 | def mostCommonWord(self, paragraph: str, banned: List[str]) -> str: 14 | # 56ms 36% 15 | word_dict = dict.fromkeys(banned, -1) 16 | for word in re.finditer(r"[a-zA-Z]+", paragraph): 17 | word = word.group().lower() 18 | if word_dict.get(word) == -1: 19 | # 违禁词 20 | continue 21 | else: 22 | word_dict[word] = word_dict.get(word,0) +1 23 | return max(word_dict, key=lambda x:word_dict[x]) 24 | 25 | 26 | if __name__ == "__main__": 27 | paragraph = "Bob hit a ball, the hit BALL flew far after it was hit." 28 | banned = ["hit"] 29 | S = Solution() 30 | print(S.mostCommonWord(paragraph, banned)) -------------------------------------------------------------------------------- /05_leetcode/824.山羊拉丁文.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给定一个由空格分割单词的句子 S。每个单词只包含大写或小写字母。 3 | 4 | 我们要将句子转换为 “Goat Latin”(一种类似于 猪拉丁文 - Pig Latin 的虚构语言)。 5 | 6 | 山羊拉丁文的规则如下: 7 | 8 | 如果单词以元音开头(a, e, i, o, u),在单词后添加"ma"。 9 | 例如,单词"apple"变为"applema"。 10 | 11 | 如果单词以辅音字母开头(即非元音字母),移除第一个字符并将它放到末尾,之后再添加"ma"。 12 | 例如,单词"goat"变为"oatgma"。 13 | 14 | 根据单词在句子中的索引,在单词最后添加与索引相同数量的字母'a',索引从1开始。 15 | 例如,在第一个单词后添加"a",在第二个单词后添加"aa",以此类推。 16 | 返回将 S 转换为山羊拉丁文后的句子。 17 | 18 | """ 19 | 20 | class Solution: 21 | def toGoatLatin(self, S: str) -> str: 22 | # 40ms 23 | S_list = S.split() 24 | for index, word in enumerate(S_list): 25 | if word[0].lower() in 'aeiouAEIOU': 26 | S_list[index] = word + 'ma' + 'a'*(index+1) 27 | else: 28 | S_list[index] = word[1:] + word[0] + 'ma' + 'a'*(index+1) 29 | return ' '.join(S_list) 30 | 31 | def toGoatLatin2(self, S): 32 | # 44ms 33 | def convert(word): 34 | if word[0] not in 'aeiouAEIOU': 35 | word = word[1:] + word[:1] 36 | return word + 'ma' 37 | 38 | return " ".join(convert(word) + 'a' * i for i, word in enumerate(S.split(), 1)) 39 | 40 | 41 | 42 | 43 | if __name__ == "__main__": 44 | test = "I speak Goat Latin" 45 | S = Solution() 46 | print(S.toGoatLatin(test)) -------------------------------------------------------------------------------- /05_leetcode/832.翻转图像.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给定一个二进制矩阵 A,我们想先水平翻转图像,然后反转图像并返回结果。 3 | 水平翻转图片就是将图片的每一行都进行翻转,即逆序。 4 | 例如,水平翻转 [1, 1, 0] 的结果是 [0, 1, 1]。 5 | 6 | 反转图片的意思是图片中的 0 全部被 1 替换, 1 全部被 0 替换。 7 | 例如,反转 [0, 1, 1] 的结果是 [1, 0, 0]。 8 | 9 | 来源:力扣(LeetCode) 10 | 链接:https://leetcode-cn.com/problems/flipping-an-image 11 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 12 | """ 13 | class Solution: 14 | def flipAndInvertImage(self, A: list) -> list: 15 | # 3 min 27 s 60ms 16 | for index, row in enumerate(A): 17 | A[index] = [0 if i==1 else 1 for i in row[::-1]] 18 | return A 19 | 20 | def flipAndInvertImage2(self, A: list) -> list: 21 | # 84ms 22 | return [[~i+2 for i in j[::-1]] for j in A] 23 | 24 | if __name__ == "__main__": 25 | A = [[1,1,0],[1,0,1],[0,0,0]] 26 | s = Solution() 27 | print(s.flipAndInvertImage2(A)) -------------------------------------------------------------------------------- /05_leetcode/844.!生成器_比较含退格的字符串.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给定 S 和 T 两个字符串,当它们分别被输入到空白的文本编辑器后, 3 | 判断二者是否相等,并返回结果。 # 代表退格字符。 4 | 输入:S = "ab##", T = "c#d#" 5 | 输出:true 6 | 解释:S 和 T 都会变成 “”。 7 | 注意:如果对空文本输入退格字符,文本继续为空。 8 | 9 | 10 | """ 11 | 12 | 13 | class Solution: 14 | def backspaceCompare(self, S: str, T: str) -> bool: 15 | # 48ms 26.26% 16 | S_list = [] 17 | for ch in S: 18 | if ch != '#': 19 | S_list.append(ch) 20 | elif len(S_list) > 0: 21 | S_list.pop() 22 | T_list = [] 23 | for ch in T: 24 | if ch != '#': 25 | T_list.append(ch) 26 | elif len(T_list) > 0: 27 | T_list.pop() 28 | if S_list == T_list: 29 | return True 30 | else: 31 | return False 32 | 33 | def backspaceCompare2(self, S: str, T: str) -> bool: 34 | # 48ms 35 | # 反向遍历 双指针 36 | import itertools 37 | def F(S): 38 | skip = 0 39 | for x in reversed(S): 40 | if x == '#': 41 | skip += 1 42 | elif skip: 43 | skip -= 1 44 | else: 45 | yield x 46 | 47 | return all(x == y for x, y in itertools.zip_longest(F(S), F(T))) 48 | 49 | if __name__ == "__main__": 50 | S, T = "ab##", "c#d#" 51 | s = Solution() 52 | print(s.backspaceCompare2(S, T)) 53 | -------------------------------------------------------------------------------- /05_leetcode/860.柠檬水找零.py: -------------------------------------------------------------------------------- 1 | """ 2 | 在柠檬水摊上,每一杯柠檬水的售价为 5 美元。 3 | 4 | 顾客排队购买你的产品,(按账单 bills 支付的顺序)一次购买一杯。 5 | 6 | 每位顾客只买一杯柠檬水,然后向你付 5 美元、10 美元或 20 美元。你必须给每个顾客正确找零,也就是说净交易是每位顾客向你支付 5 美元。 7 | 8 | 注意,一开始你手头没有任何零钱。 9 | 10 | 如果你能给每位顾客正确找零,返回 true ,否则返回 false 。 11 | 12 | 来源:力扣(LeetCode) 13 | 链接:https://leetcode-cn.com/problems/lemonade-change 14 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 15 | """ 16 | 17 | class Solution: 18 | def lemonadeChange(self, bills: list) -> bool: 19 | # 184ms 47% 模拟情景 20 | money_dict = {5:0, 10:0, 20:0} 21 | for bill in bills: 22 | money_dict[bill] += 1 23 | change = bill - 5 24 | while change > 0: 25 | if 10 <= change and money_dict[10] > 0: 26 | change -= 10 27 | money_dict[10] -= 1 28 | elif 5 <= change and money_dict[5] > 0: 29 | change -= 5 30 | money_dict[5] -= 1 31 | else: 32 | return False 33 | else: 34 | return True 35 | 36 | 37 | 38 | if __name__ == "__main__": 39 | test = [5,5,10,10,20] 40 | s = Solution() 41 | print(s.lemonadeChange2(test)) -------------------------------------------------------------------------------- /05_leetcode/876.链表的中间结点.py: -------------------------------------------------------------------------------- 1 | # 2 | # @lc app=leetcode.cn id=876 lang=python3 3 | # 4 | # [876] 链表的中间结点 5 | # 6 | class ListNode: 7 | def __init__(self, val=0, next=None): 8 | self.val = val 9 | self.next = next 10 | 11 | # @lc code=start 12 | # Definition for singly-linked list. 13 | class Solution: 14 | # def middleNode(self, head: ListNode) -> ListNode: 15 | # ''' 16 | # 50% 15.1% 17 | # ''' 18 | # slow = fast = head 19 | # count = 0 20 | # while fast.next is not None: 21 | # fast = fast.next 22 | # count += 1 23 | # if count == 2: 24 | # count = 0 25 | # slow = slow.next 26 | # else: 27 | # if count == 1: 28 | # slow = slow.next 29 | 30 | 31 | # return slow 32 | 33 | def middleNode(self, head: ListNode) -> ListNode: 34 | ''' 35 | 88.4% 5.17% 36 | ''' 37 | slow = fast = head 38 | while fast and fast.next: 39 | slow = slow.next 40 | fast = fast.next.next 41 | 42 | return slow 43 | # @lc code=end 44 | 45 | -------------------------------------------------------------------------------- /05_leetcode/883.三维形体投影面积.py: -------------------------------------------------------------------------------- 1 | """ 2 | 在 N * N 的网格中,我们放置了一些与 x,y,z 三轴对齐的 1 * 1 * 1 立方体。 3 | 4 | 每个值 v = grid[i][j] 表示 v 个正方体叠放在单元格 (i, j) 上。 5 | 6 | 现在,我们查看这些立方体在 xy、yz 和 zx 平面上的投影。 7 | 8 | 投影就像影子,将三维形体映射到一个二维平面上。 9 | 10 | 在这里,从顶部、前面和侧面看立方体时,我们会看到“影子”。 11 | 12 | 返回所有三个投影的总面积。 13 | 14 | 来源:力扣(LeetCode) 15 | 链接:https://leetcode-cn.com/problems/projection-area-of-3d-shapes 16 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 17 | """ 18 | 19 | class Solution: 20 | def projectionArea(self, grid: list) -> int: 21 | xy, xz, yz = len(grid)**2, 0, 0 22 | 23 | for item in grid: 24 | xz += max(item) 25 | 26 | for i in range(len(grid)): 27 | yz += max([item[i] for item in grid]) 28 | 29 | for item in grid: 30 | xy -= item.count(0) 31 | 32 | return xy+xz+yz 33 | 34 | 35 | if __name__ == "__main__": 36 | test = [[1,2],[3,4]] 37 | s1 = Solution() 38 | print(s1.projectionArea(test)) -------------------------------------------------------------------------------- /05_leetcode/888.公平的糖果交换.py: -------------------------------------------------------------------------------- 1 | """ 2 | 爱丽丝和鲍勃有不同大小的糖果棒:A[i] 是爱丽丝拥有的第 i 块糖的大小,B[j] 是鲍勃拥有的第 j 块糖的大小。 3 | 4 | 因为他们是朋友,所以他们想交换一个糖果棒,这样交换后,他们都有相同的糖果总量。 5 | (一个人拥有的糖果总量是他们拥有的糖果棒大小的总和。) 6 | 7 | 返回一个整数数组 ans,其中 ans[0] 是爱丽丝必须交换的糖果棒的大小,ans[1] 是 Bob 必须交换的糖果棒的大小。 8 | 9 | 如果有多个答案,你可以返回其中任何一个。保证答案存在。 10 | """ 11 | 12 | class Solution: 13 | def fairCandySwap(self, A: list, B: list) -> list: 14 | # 576ms 12.3% 15 | A_total, B_total = sum(A), sum(B) 16 | B_s = set(B) # 转换成集合后会提升in的速度 17 | for a in A: 18 | b = a - (A_total - B_total) // 2 19 | if b in B_s: 20 | return [a, b] 21 | 22 | def fairCandySwap2(self, A: list, B: list) -> list: 23 | # 456ms 71.43 24 | Sa, Sb = sum(A), sum(B) 25 | setB = set(B) 26 | for x in A: 27 | if x + (Sb - Sa) // 2 in setB: 28 | return [x, x + (Sb - Sa) // 2] 29 | 30 | 31 | if __name__ == "__main__": 32 | A = [1, 2, 5] 33 | B = [2, 4] 34 | s = Solution() 35 | print(s.fairCandySwap2(A, B)) -------------------------------------------------------------------------------- /05_leetcode/9.回文数.py: -------------------------------------------------------------------------------- 1 | """ 2 | 判断一个整数是否是回文数。 3 | 回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。 4 | """ 5 | class Solution: 6 | def isPalindrome(self, x: int) -> bool: 7 | if x < 0: 8 | return False 9 | # 字符串法分析 10 | x_str = str(x) 11 | rts_x = ''.join(reversed(x_str)) 12 | 13 | if x_str != rts_x: 14 | return False 15 | elif len(x_str) > 1 and rts_x[0] == 0: 16 | # 数字长度大于1 且个位为0 17 | return False 18 | else: 19 | return True 20 | 21 | if __name__ == "__main__": 22 | s = Solution() 23 | print(s.isPalindrome(10)) -------------------------------------------------------------------------------- /05_leetcode/905.按奇偶排序数组.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给定一个非负整数数组 A,返回一个数组,在该数组中, 3 | A 的所有偶数元素之后跟着所有奇数元素。 4 | 5 | 你可以返回满足此条件的任何数组作为答案。 6 | 922 II 7 | """ 8 | 9 | class Solution: 10 | def sortArrayByParity(self, A: list) -> list: 11 | # 88ms 82% 双指针 交换奇数到尾部 12 | front, rear = 0, len(A)-1 13 | while front < rear: 14 | if A[front] % 2 == 0: 15 | # 偶数 16 | front += 1 17 | else: 18 | A[front], A[rear] = A[rear], A[front] 19 | rear -= 1 20 | return A 21 | 22 | def sortArrayByParity2(self, A:list) -> list: 23 | # 92ms 24 | front, rear = 0, len(A) - 1 25 | while True: 26 | while front < len(A) and A[front] % 2 == 0: 27 | # 找奇数 28 | front += 1 29 | while 0 < rear and A[rear] % 2 == 1: 30 | # 找偶数 31 | rear -= 1 32 | if front < rear: 33 | A[front], A[rear] = A[rear], A[front] 34 | else: 35 | break 36 | 37 | return A 38 | 39 | 40 | if __name__ == "__main__": 41 | test = [3,1,2,4] 42 | s = Solution() 43 | print(s.sortArrayByParity2(test)) 44 | -------------------------------------------------------------------------------- /05_leetcode/908.最小差值I.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给你一个整数数组 A,对于每个整数 A[i], 3 | 我们可以选择处于区间 [-K, K] 中的任意数 x , 4 | 将 x 与 A[i] 相加,结果存入 A[i] 。 5 | 6 | 在此过程之后,我们得到一些数组 B。 7 | 返回 B 的最大值和 B 的最小值之间可能存在的最小差值。 8 | """ 9 | class Solution: 10 | def smallestRangeI(self, A: list, K: int) -> int: 11 | # 152 ms 44% 12 | m, n = max(A), min(A) 13 | return max(m - n - 2*K, 0) 14 | 15 | def smallestRangeI2(self, A: list, K: int) -> int: 16 | # 132 ms 87% 17 | m, n = 0, 10000 18 | for num in A: 19 | if num > m: 20 | m = num 21 | if num < n: 22 | n = num 23 | return max(m - n - 2*K, 0) 24 | 25 | 26 | if __name__ == "__main__": 27 | A, k = [1, 3, 6], 3 28 | S = Solution() 29 | print(S.smallestRangeI2(A, k)) -------------------------------------------------------------------------------- /05_leetcode/914.卡牌分组.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给定一副牌,每张牌上都写着一个整数。 3 | 4 | 此时,你需要选定一个数字 X,使我们可以将整副牌按下述规则分成 1 组或更多组: 5 | 6 | 每组都有 X 张牌。 7 | 组内所有的牌上都写着相同的整数。 8 | 9 | 仅当你可选的 X >= 2 时返回 true。 10 | 11 | 来源:力扣(LeetCode) 12 | 链接:https://leetcode-cn.com/problems/x-of-a-kind-in-a-deck-of-cards 13 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 14 | """ 15 | from typing import List 16 | from collections import Counter 17 | 18 | class Solution: 19 | def hasGroupsSizeX(self, deck: List[int]) -> bool: 20 | # 48ms 75% 每个卡号重复次数存在大于2的最大公约数 True 21 | if not (freq_dict:=Counter(deck)): 22 | return False 23 | 24 | temp = min(freq_dict.values()) # 重复数量最小的号码 25 | if temp < 2: 26 | return False 27 | 28 | # 所有的数字有公约数 29 | for i in range(2, temp+1): 30 | for v in freq_dict.values(): 31 | if v % i != 0: 32 | break 33 | else: 34 | # i 为公约数 35 | return True 36 | else: 37 | return False 38 | 39 | 40 | if __name__ == "__main__": 41 | test = [1,1,1,1,2,2,2,2,2] 42 | S = Solution() 43 | print(S.hasGroupsSizeX(test)) -------------------------------------------------------------------------------- /05_leetcode/922.按奇偶排序数组II.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给定一个非负整数数组 A, A 中一半整数是奇数,一半整数是偶数。 3 | 4 | 对数组进行排序,以便当 A[i] 为奇数时,i 也是奇数;当 A[i] 为偶数时, i 也是偶数。 5 | 6 | 你可以返回任何满足上述条件的数组作为答案。 7 | 905 I 8 | """ 9 | 10 | class Solution: 11 | def sortArrayByParityII(self, A: list) -> list: 12 | # 244 ms 71.34% 双指针 13 | odd, even = 0, 1 # 寻找错位奇数和错位偶数 14 | while odd < len(A): 15 | if A[odd] % 2 == 1: 16 | # 找到错位奇数 17 | if A[even] % 2 == 0: 18 | # 找到错位偶数 19 | A[odd], A[even] = A[even], A[odd] 20 | else: 21 | even += 2 22 | else: 23 | odd += 2 24 | return A 25 | 26 | def sortArrayByParityII2(self, A): 27 | # 遍历两次A 236ms 28 | ans = [None] * len(A) 29 | ans[::2] = (x for x in A if x % 2 == 0) 30 | ans[1::2] = (x for x in A if x % 2 == 1) 31 | 32 | return ans 33 | 34 | 35 | if __name__ == "__main__": 36 | s = Solution() 37 | print(s.sortArrayByParityII2([4, 2, 5, 7, 9, 9, 6, 6])) 38 | -------------------------------------------------------------------------------- /05_leetcode/925.长按键入.py: -------------------------------------------------------------------------------- 1 | """ 2 | 你的朋友正在使用键盘输入他的名字 name。偶尔,在键入字符 c 时,按键可能会被长按,而字符可能被输入 1 次或多次。 3 | 4 | 你将会检查键盘输入的字符 typed。如果它对应的可能是你的朋友的名字(其中一些字符可能被长按),那么就返回 True。 5 | 6 | """ 7 | 8 | class Solution: 9 | def isLongPressedName(self, name: str, typed: str) -> bool: 10 | # 双指针 44ms 42.57% 11 | index_t = 0 12 | for index, ch in enumerate(name): 13 | if index_t >= len(typed) or typed[index_t] != ch: 14 | # 输入已比对完 或字符不匹配 15 | return False 16 | elif index+1 < len(name) and name[index+1] == ch: 17 | # 名字中有连续字符 18 | index_t += 1 19 | else: 20 | # index_t 字符与 ch一致且ch不连续 21 | while index_t < len(typed) and typed[index_t] == ch: 22 | index_t += 1 23 | else: 24 | # name部分已经被打出 25 | if index_t < len(typed): 26 | # typed结尾有不同的字符 27 | return False 28 | 29 | return True 30 | 31 | 32 | def isLongPressedName2(self, name, typed): 33 | # 按块分组 34 | import itertools 35 | g1 = [(k, len(list(grp))) for k, grp in itertools.groupby(name)] 36 | print(g1) 37 | g2 = [(k, len(list(grp))) for k, grp in itertools.groupby(typed)] 38 | if len(g1) != len(g2): 39 | return False 40 | 41 | return all(k1 == k2 and v1 <= v2 42 | for (k1,v1), (k2,v2) in zip(g1, g2)) 43 | 44 | 45 | 46 | 47 | 48 | if __name__ == "__main__": 49 | name, typed = "saeed", "ssaaedd" 50 | # name, typed = "saeed", "ssaaeedd" 51 | s = Solution() 52 | print(s.isLongPressedName2(name, typed)) 53 | -------------------------------------------------------------------------------- /05_leetcode/929.独特的电子邮件.py: -------------------------------------------------------------------------------- 1 | """ 2 | 每封电子邮件都由一个本地名称和一个域名组成,以 @ 符号分隔。 3 | 4 | 例如,在 alice@leetcode.com中, alice 是本地名称,而 leetcode.com 是域名。 5 | 6 | 除了小写字母,这些电子邮件还可能包含 '.' 或 '+'。 7 | 8 | 如果在电子邮件地址的本地名称部分中的某些字符之间添加句点('.'),则发往那里的邮件将会转发到本地名称中没有点的同一地址。例如,"alice.z@leetcode.com” 和 “alicez@leetcode.com” 会转发到同一电子邮件地址。 (请注意,此规则不适用于域名。) 9 | 10 | 如果在本地名称中添加加号('+'),则会忽略第一个加号后面的所有内容。这允许过滤某些电子邮件,例如 m.y+name@email.com 将转发到 my@email.com。 (同样,此规则不适用于域名。) 11 | 12 | 可以同时使用这两个规则。 13 | 14 | 给定电子邮件列表 emails,我们会向列表中的每个地址发送一封电子邮件。实际收到邮件的不同地址有多少? 15 | 16 | 来源:力扣(LeetCode) 17 | 链接:https://leetcode-cn.com/problems/unique-email-addresses 18 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 19 | """ 20 | class Solution: 21 | def numUniqueEmails(self, emails: list) -> int: 22 | s = set() 23 | for email in emails: 24 | local, domain = email.split('@') 25 | plus = local.find('+') 26 | if plus != -1: 27 | local = local[:plus].replace('.', '') 28 | local = local.replace('.', '') 29 | s.add(local+'@' +domain) 30 | return len(s) 31 | 32 | if __name__ == "__main__": 33 | test = ["test.email+alex@leetcode.com","test.e.mail+bob.cathy@leetcode.com","testemail+david@lee.tcode.com"] 34 | s = Solution() 35 | print(s.numUniqueEmails(test)) -------------------------------------------------------------------------------- /05_leetcode/937.重新排列日志文件.py: -------------------------------------------------------------------------------- 1 | """ 2 | 你有一个日志数组 logs。每条日志都是以 空格分隔的字串。 3 | 4 | 对于每条日志,其第一个字为字母与数字混合的 标识符。 5 | 6 | - 除标识符之外,所有字均由小写字母组成的,称为 字母日志 7 | - 除标识符之外,所有字均由数字组成的,称为 数字日志 8 | 9 | 题目所用数据保证每个日志在其标识符后面至少有一个字。 10 | 11 | 请按下述规则将日志重新排序: 12 | 13 | - 所有 字母日志 都排在 数字日志 之前。 14 | - 字母日志 在内容不同时,忽略标识符后,按内容字母顺序排序;在内容相同时,按标识符排序; 15 | - 数字日志 应该按原来的顺序排列。 16 | 17 | 返回日志的最终顺序。 18 | """ 19 | from typing import List 20 | 21 | class Solution: 22 | def reorderLogFiles(self, logs: List[str]) -> List[str]: 23 | # 52ms sort 元组key 24 | def comput_weight(log): 25 | tag, content = log.split(' ', 1) 26 | if content[0].isalpha(): 27 | return (0, content, tag) 28 | else: 29 | return (1,) 30 | 31 | logs.sort(key=lambda x:comput_weight(x)) 32 | return logs 33 | 34 | 35 | if __name__ == "__main__": 36 | log1 =["t kvr", "r 3 1", "i 403", "7 so", "t 54"] 37 | S = Solution() 38 | print(S.reorderLogFiles2(log1)) -------------------------------------------------------------------------------- /05_leetcode/94.二叉树的中序遍历.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给定一个二叉树返回它的中序遍历 3 | """ 4 | # Definition for a binary tree node. 5 | class TreeNode: 6 | def __init__(self, x): 7 | self.val = x 8 | self.left = None 9 | self.right = None 10 | 11 | class Solution: 12 | def inorderTraversal(self, root: TreeNode) -> List[int]: 13 | # 递归解法 14 | result = [] 15 | if not root: 16 | return result 17 | result.extend(self.inorderTraversal(root.left)) 18 | result.append(root.val) 19 | result.extend(self.inorderTraversal(root.right)) 20 | return result 21 | 22 | 23 | def inorderTraversal2(self, root: TreeNode) -> List[int]: 24 | # 非递归解法 25 | stack, result = [], [] 26 | 27 | # 初始化 root及其左链入栈 28 | while root != None: 29 | stack.append(root) 30 | root = root.left 31 | 32 | # 迭代遍历 33 | while len(stack)>0: 34 | # 栈非空即未完成遍历 35 | root = stack.pop() 36 | result.append(root.val) 37 | # root右孩子right 其right其左链入栈 38 | root = root.right 39 | while root != None: 40 | stack.append(root) 41 | root = root.left 42 | 43 | return result 44 | 45 | 46 | if __name__ == "__main__": 47 | -------------------------------------------------------------------------------- /05_leetcode/941.有效的山脉数组.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给定一个整数数组 A,如果它是有效的山脉数组就返回 true,否则返回 false。 3 | 让我们回顾一下,如果 A 满足下述条件,那么它是一个山脉数组: 4 | 5 | A.length >= 3 6 | 在 0 < i < A.length - 1 条件下,存在 i 使得: 7 | A[0] < A[1] < ... A[i-1] < A[i] 8 | A[i] > A[i+1] > ... > A[A.length - 1] 9 | 10 | 来源:力扣(LeetCode) 11 | 链接:https://leetcode-cn.com/problems/valid-mountain-array 12 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 13 | """ 14 | 15 | class Solution: 16 | def validMountainArray(self, A: list) -> bool: 17 | if len(A) < 3: 18 | return False 19 | prvious = A[0] 20 | for i in range(1, len(A)): 21 | if A[i] == prvious: 22 | return False 23 | elif A[i] > prvious: 24 | prvious = A[i] 25 | else: 26 | break 27 | 28 | if i == len(A) or i == 1: 29 | # 只有一半山脉 30 | return False 31 | 32 | for j in range(i, len(A)): 33 | if A[j] == prvious: 34 | return False 35 | elif A[j] < prvious: 36 | prvious = A[j] 37 | else: 38 | prvious = A[j] 39 | return False 40 | return True 41 | 42 | if __name__ == "__main__": 43 | s1 = Solution() 44 | # print(s1.validMountainArray([2,1])) 45 | # print(s1.validMountainArray([3,5,5])) 46 | # print(s1.validMountainArray([0,3,2,1])) 47 | 48 | print(s1.validMountainArray([9,8,7,6,5,4,3,2,1,0])) 49 | -------------------------------------------------------------------------------- /05_leetcode/961.重复N次的元素.py: -------------------------------------------------------------------------------- 1 | """ 2 | 在大小为 2N 的数组 A 中有 N+1 个不同的元素,其中有一个元素重复了 N 次。 3 | 4 | 返回重复了 N 次的那个元素。 5 | """ 6 | 7 | class Solution: 8 | def repeatedNTimes(self, A) -> int: 9 | from random import randint 10 | while True: 11 | i = randint(0, len(A)-1) 12 | j = randint(0, len(A)-1) 13 | if i != j and A[i] == A[j]: 14 | return A[i] 15 | -------------------------------------------------------------------------------- /05_leetcode/970.强整数.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给定两个正整数 x 和 y,如果某一整数等于 x^i + y^j,其中整数 i >= 0 且 j >= 0,那么我们认为该整数是一个强整数。 3 | 4 | 返回值小于或等于 bound 的所有强整数组成的列表。 5 | 6 | 你可以按任何顺序返回答案。在你的回答中,每个值最多出现一次。 7 | 8 | e.g. 9 | 输入:x = 2, y = 3, bound = 10 10 | 输出:[2,3,4,5,7,9,10] 11 | """ 12 | from typing import List 13 | from math import log 14 | 15 | class Solution: 16 | def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]: 17 | # 44ms 60% 18 | ans = set() 19 | i_max = int(log(bound, x)) if x != 1 else 1 20 | j_max = int(log(bound, y)) if y != 1 else 1 21 | for i in range(0, i_max+1): 22 | for j in range(0, j_max+1): 23 | interger = x**i + y**j 24 | if interger <= bound: 25 | ans.add(interger) 26 | return list(ans) 27 | 28 | def powerfulIntegers2(self, x, y, bound): 29 | # 68ms 18% 30 | ans = set() 31 | # 2**20 > bound bound <= 10 ** 6 32 | for i in range(20): 33 | for j in range(20): 34 | v = x**i + y**j 35 | if v <= bound: 36 | ans.add(v) 37 | return list(ans) 38 | 39 | 40 | if __name__ == "__main__": 41 | S = Solution() 42 | x, y, bound = 3, 5 ,15 43 | print(S.powerfulIntegers(x, y, bound)) -------------------------------------------------------------------------------- /05_leetcode/973.最接近远点的K个点.py: -------------------------------------------------------------------------------- 1 | """ 2 | 我们有一个由平面上的点组成的列表 points。需要从中找出 K 个距离原点 (0, 0) 最近的点。 3 | 4 | (这里,平面上两点之间的距离是欧几里德距离。) 5 | 6 | 你可以按任何顺序返回答案。除了点坐标的顺序之外,答案确保是唯一的。 7 | """ 8 | from typing import List 9 | 10 | class Solution: 11 | def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]: 12 | # 804ms 70.67% 13 | points.sort(key=lambda point:(point[0]**2 +point[1]**2)**(1/2)) 14 | return points[0:K] 15 | 16 | 17 | if __name__ == "__main__": 18 | points = [[1,3],[-2,2]] 19 | k = 1 20 | S = Solution() 21 | print(S.kClosest(points, k)) -------------------------------------------------------------------------------- /05_leetcode/98.验证二叉搜索树.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给定一个二叉树,判断其是否是一个有效的二叉搜索树。 3 | 4 | 假设一个二叉搜索树具有如下特征: 5 | 6 | 节点的左子树只包含小于当前节点的数。 7 | 节点的右子树只包含大于当前节点的数。 8 | 所有左子树和右子树自身必须也是二叉搜索树。 9 | 10 | 11 | 来源:力扣(LeetCode) 12 | 链接:https://leetcode-cn.com/problems/validate-binary-search-tree 13 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 14 | """ 15 | 16 | 17 | # Definition for a binary tree node. 18 | class TreeNode: 19 | def __init__(self, x): 20 | self.val = x 21 | self.left = None 22 | self.right = None 23 | 24 | class Solution: 25 | def isValidBST(self, root: TreeNode) -> bool: 26 | # 错误 仅仅递归判断 左 < x < 右 27 | if not root: 28 | return True 29 | if root.left and root.left.val >= root.val: 30 | return False 31 | if root.right and root.right.val <= root.val: 32 | return False 33 | return self.isValidBST(root.right) and self.isValidBST(root.left) 34 | 35 | def isValidBST(self, root: TreeNode) -> bool: 36 | # 中序遍历递增 非递归 左入栈 出栈后访问 并入栈右侧 37 | temp = root 38 | queue, last = [], None 39 | while temp: 40 | queue.append(temp) 41 | temp = temp.left 42 | while queue: 43 | temp = queue.pop() 44 | if last is not None: 45 | if temp.val <= last: 46 | return False 47 | last = temp.val 48 | if temp.right: 49 | # 存在右节点 则将右节点左链入栈 50 | temp = temp.right 51 | while temp: 52 | queue.append(temp) 53 | temp = temp.left 54 | return True 55 | 56 | 57 | -------------------------------------------------------------------------------- /05_leetcode/983.!!动态规划_最低票价.py: -------------------------------------------------------------------------------- 1 | """ 2 | 在一个火车旅行很受欢迎的国度,你提前一年计划了一些火车旅行。 3 | 在接下来的一年里,你要旅行的日子将以一个名为 days 的数组给出。 4 | 每一项是一个从 1 到 365 的整数。 5 | 6 | 火车票有三种不同的销售方式: 7 | 8 | 一张为期一天的通行证售价为 costs[0] 美元; 9 | 一张为期七天的通行证售价为 costs[1] 美元; 10 | 一张为期三十天的通行证售价为 costs[2] 美元。 11 | 通行证允许数天无限制的旅行。 12 | 13 | 例如,如果我们在第 2 天获得一张为期 7 天的通行证, 14 | 那么我们可以连着旅行 7 天: 15 | 第 2 天、第 3 天、第 4 天、第 5 天、第 6 天、第 7 天和第 8 天。 16 | 17 | 返回你想要完成在给定的列表 days 中列出的每一天的旅行所需要的最低消费。 18 | 19 | 来源:力扣(LeetCode) 20 | 链接:https://leetcode-cn.com/problems/minimum-cost-for-tickets 21 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 22 | """ 23 | from typing import List 24 | from functools import lru_cache 25 | 26 | class Solution: 27 | def mincostTickets(self, days: List[int], costs: List[int]) -> int: 28 | # 日期变量型 68ms 34.06% 29 | dayset = set(days) 30 | durations = [1, 7, 30] 31 | 32 | @lru_cache(None) # 记录记录函数的调用结果 直接使用之前的返回值 33 | def dp(i): 34 | if i > 365: 35 | return 0 36 | elif i in dayset: 37 | return min(dp(i + d) + c for c, d in zip(costs, durations)) 38 | else: 39 | return dp(i + 1) 40 | 41 | return dp(1) 42 | 43 | 44 | 45 | if __name__ == "__main__": 46 | days = [1, 4, 6, 7, 8, 20] 47 | costs = [2, 7, 15] 48 | S = Solution() 49 | print(S.mincostTickets(days, costs)) 50 | -------------------------------------------------------------------------------- /05_leetcode/989.数组形式的整数加法.py: -------------------------------------------------------------------------------- 1 | """ 2 | 对于非负整数 X 而言,X 的数组形式是每位数字按从左到右的顺序形成的数组。 3 | 例如,如果 X = 1231,那么其数组形式为 [1,2,3,1]。 4 | 5 | 给定非负整数 X 的数组形式 A,返回整数 X+K 的数组形式。 6 | 7 | """ 8 | from typing import List 9 | 10 | class Solution: 11 | def addToArrayForm(self, A: List[int], K: int) -> List[int]: 12 | # 400ms 54.73% 13 | carry = 0 14 | index = len(A) - 1 15 | while K != 0: 16 | K, add = divmod(K, 10) 17 | if index >= 0: 18 | carry, add = divmod(add + carry + A[index], 10) 19 | A[index] = add 20 | index -= 1 21 | else: 22 | carry, add = divmod(add + carry, 10) 23 | A.insert(0, add) 24 | while carry: 25 | if index >= 0: 26 | carry, A[index] = divmod(carry + A[index], 10) 27 | index -= 1 28 | else: 29 | A.insert(0, carry) 30 | carry = 0 31 | return A 32 | 33 | def addToArrayForm2(self, A, K): 34 | # 344ms 80.56% 直接全部加在最低位 逐位取模 35 | A[-1] += K 36 | for i in range(len(A) - 1, -1, -1): 37 | carry, A[i] = divmod(A[i], 10) 38 | if i: 39 | # i 不等于0 40 | A[i-1] += carry 41 | if carry: 42 | A = list(map(int, str(carry))) + A 43 | return A 44 | 45 | 46 | 47 | 48 | 49 | if __name__ == "__main__": 50 | # A, K = [1,2,0,0], 34 51 | # A, K = [0], 34 52 | # A, K = [7, 7], 34 53 | A, K = [9,9,9,9,9,9,9,9,9,9], 1 54 | S = Solution() 55 | print(S.addToArrayForm(A, K)) -------------------------------------------------------------------------------- /05_leetcode/JZOF.36.二叉搜索树与双向链表.py: -------------------------------------------------------------------------------- 1 | #! -*- encoding:utf-8 -*- 2 | """ 3 | @File : JZOF.36.二叉搜索树与双向链表.py 4 | @Author : Zachary Li 5 | @Contact : li_zaaachary@163.com 6 | @Dscpt : 7 | https://leetcode-cn.com/problems/er-cha-sou-suo-shu-yu-shuang-xiang-lian-biao-lcof/ 8 | """ 9 | 10 | # Definition for a Node. 11 | class Node: 12 | def __init__(self, val, left=None, right=None): 13 | self.val = val 14 | self.left = left 15 | self.right = right 16 | 17 | class Solution: 18 | def treeToDoublyList(self, root: 'Node') -> 'Node': 19 | pass 20 | 21 | if __name__ == "__main__": 22 | pass -------------------------------------------------------------------------------- /05_leetcode/JZOF.38.字符串的排列.py: -------------------------------------------------------------------------------- 1 | #! -*- encoding:utf-8 -*- 2 | """ 3 | @File : Offer38.字符串的排列.py 4 | @Author : Zachary Li 5 | @Contact : li_zaaachary@163.com 6 | @Dscpt : https://leetcode-cn.com/problems/zi-fu-chuan-de-pai-lie-lcof/ 7 | 8 | 输入一个字符串,打印出该字符串中字符的所有排列。 9 | 10 | 你可以以任意顺序返回这个字符串数组,但里面不能有重复元素。 11 | """ 12 | from typing import List 13 | import itertools 14 | 15 | class Solution: 16 | def permutation(self, s: str) -> List[str]: 17 | # 97% 18 | return list(set([''.join(item) for item in itertools.permutations(s)])) 19 | 20 | def permutation2(self, s: str) -> List[str]: 21 | list_s, res = list(s), [] 22 | def DFS(current_len): 23 | # 目前已经确定了 current_len 之前的字符 24 | nonlocal res, list_s 25 | if current_len == len(list_s) - 1: 26 | res.append(''.join(list_s)) 27 | return 28 | temp_dict = set() 29 | # 将 current_len 与 30 | for i in range(current_len, len(list_s)): 31 | # 重复则剪枝 32 | if list_s[i] in temp_dict: continue 33 | temp_dict.add(list_s[i]) 34 | # 交换,将 list_s[i] 固定在 current_len 的位置 35 | list_s[i], list_s[current_len] = list_s[current_len], list_s[i] 36 | DFS(current_len + 1) 37 | list_s[i], list_s[current_len] = list_s[current_len], list_s[i] # 回溯 38 | 39 | DFS(0) 40 | return res 41 | 42 | 43 | if __name__ == "__main__": 44 | S = Solution() 45 | print(S.permutation2('abc')) -------------------------------------------------------------------------------- /05_leetcode/JZOF.44.数字序列中某一位的数字.py: -------------------------------------------------------------------------------- 1 | #! -*- encoding:utf-8 -*- 2 | """ 3 | @File : Offer 44.数字序列中某一位的数字.py 4 | @Author : Zachary Li 5 | @Contact : li_zaaachary@163.com 6 | @Dscpt : 迭代 + 求整 / 求余 7 | 8 | https://leetcode-cn.com/problems/shu-zi-xu-lie-zhong-mou-yi-wei-de-shu-zi-lcof/solution/mian-shi-ti-44-shu-zi-xu-lie-zhong-mou-yi-wei-de-6/ 9 | """ 10 | 11 | class Solution: 12 | def findNthDigit(self, n: int) -> int: 13 | # 40ms 64.14% 14 | # 10x1, 90x2, 900x3, 9000x4, 90000x5 15 | level, size = 10, 1 16 | 17 | while n >= level*size: 18 | n -= level*size 19 | size += 1 20 | level = 9 * 10 ** (size-1) 21 | else: 22 | d, m = divmod(n, size) 23 | temp = 10 ** (size-1) + d if size > 1 else d 24 | return int(str(temp)[m]) 25 | 26 | 27 | 28 | 29 | if __name__ == "__main__": 30 | S = Solution() 31 | # test = [0, 5, 10, 13, 19] # 0, 5, 1, 1, 4 32 | # test = [0, 5, 10, 13, 19] # 0, 5, 1, 1, 4 33 | # print([S.findNthDigit(i) for i in range(0,30)]) 34 | # print([S.findNthDigit(i) for i in range(10,30)]) 35 | # print([S.findNthDigit(i) for i in range(80,120)]) 36 | print([S.findNthDigit(i) for i in range(150, 230)]) 37 | # print(S.findNthDigit(100)) -------------------------------------------------------------------------------- /05_leetcode/JZOF.48.最长不含重复字符的子字符串.py: -------------------------------------------------------------------------------- 1 | #! -*- encoding:utf-8 -*- 2 | """ 3 | @File : Offer 48 最长不含重复字符的子字符串.py 4 | @Author : Zachary Li 5 | @Contact : li_zaaachary@163.com 6 | @Dscpt : 7 | 请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。 8 | 9 | 输入: "abcabcbb" 10 | 输出: 3 11 | 解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。 12 | 13 | """ 14 | #%% 15 | class Solution: 16 | def lengthOfLongestSubstring_bad(self, s: str) -> int: 17 | # 暴力法 5% 18 | if len(s) <= 1: 19 | return len(s) 20 | max_len = 1 21 | for left in range(len(s)): 22 | right = left + 1 23 | while len(set(s[left:right])) == right-left: 24 | max_len = max(max_len, right-left) 25 | right += 1 26 | return max_len 27 | 28 | def lengthOfLongestSubstring(self, s: str) -> int: 29 | # 暴力法 5% 30 | if len(s) <= 1: 31 | return len(s) 32 | max_len = 1 33 | for left in range(len(s)): 34 | right = left + 1 35 | while len(set(s[left:right])) == right-left: 36 | max_len = max(max_len, right-left) 37 | right += 1 38 | return max_len 39 | 40 | #%% 41 | if __name__ == "__main__": 42 | S = Solution() 43 | print(S.lengthOfLongestSubstring('pwwkew')) 44 | # %% 45 | -------------------------------------------------------------------------------- /05_leetcode/M01.01_判断字符是否唯一.py: -------------------------------------------------------------------------------- 1 | """ 2 | 实现一个算法确定一个字符串s的所有字符是否全都不同 3 | """ 4 | 5 | 6 | class Solution: 7 | def isUnique(self, astr: str) -> bool: 8 | # 44ms 9 | ch_dict = {} 10 | for ch in astr: 11 | if ch in ch_dict: 12 | return False 13 | else: 14 | ch_dict[ch] = 1 15 | else: 16 | return True 17 | 18 | def isUnique2(self, astr: str) -> bool: 19 | # 40ms 位法 20 | mark = 0 21 | for char in astr: 22 | move_bit = ord(char) - ord('a') # 当前字母的偏移 23 | if (mark & (1 << move_bit)) != 0: # mark 和此字符串 与 24 | return False # 不为零则表示有字幕出现两次 25 | else: 26 | mark |= (1 << move_bit) # 将当前字母添加到 mark 27 | return True 28 | 29 | 30 | if __name__ == "__main__": 31 | # test = "leetcode" 32 | test = "let" 33 | s = Solution() 34 | print(s.isUnique(test)) 35 | -------------------------------------------------------------------------------- /05_leetcode/M01.04_回文排列.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给定一个字符串,编写一个函数判定其是否为某个回文串的排列之一。 3 | 4 | 回文串是指正反两个方向都一样的单词或短语。排列是指字母的重新排列。 5 | 6 | 回文串不一定是字典当中的单词。 7 | 8 | 9 | 判断字符串能否重写排列成回文 10 | """ 11 | from collections import Counter 12 | 13 | class Solution: 14 | def canPermutePalindrome(self, s: str) -> bool: 15 | # 48ms 23.76% 两个及以上字符出现次数为奇数 16 | ch_dict = Counter(s) 17 | odd = 0 18 | for value in ch_dict.values(): 19 | if value %2 ==1: 20 | if (odd:=odd+1) > 1: 21 | return False 22 | return True 23 | 24 | 25 | if __name__ == "__main__": 26 | S = Solution() 27 | print(S.canPermutePalindrome("ab")) -------------------------------------------------------------------------------- /05_leetcode/M17_打印1到最大的n位数.py: -------------------------------------------------------------------------------- 1 | """ 2 | 输入数字 n,按顺序打印出从 1 到最大的 n 位十进制数。 3 | 比如输入 3,则打印出 1、2、3 一直到最大的 3 位数 999。 4 | """ 5 | 6 | class Solution: 7 | def printNumbers(self, n: int) ->list: 8 | return [num for num in range(1, 10**n)] 9 | 10 | -------------------------------------------------------------------------------- /05_leetcode/Offer 56.I 数组中数字出现的次数.py: -------------------------------------------------------------------------------- 1 | #! -*- encoding:utf-8 -*- 2 | """ 3 | @File : Offer 56.I 数组中数字出现的次数.py 4 | @Author : Zachary Li 5 | @Contact : li_zaaachary@163.com 6 | @Dscpt : 一个整型数组 nums 里除两个数字之外,其他数字都出现了两次。请写程序找出这两个只出现一次的数字。要求时间复杂度是O(n),空间复杂度是O(1)。 7 | 8 | 输入:nums = [4,1,4,6] 9 | 输出:[1,6] 或 [6,1] 10 | """ 11 | from typing import List 12 | 13 | 14 | class Solution: 15 | def singleNumbers(self, nums: List[int]) -> List[int]: 16 | ''' 17 | 异或做法 56ms, 77.83% 18 | ''' 19 | if len(nums) < 2: 20 | return 21 | 22 | eor = 0 23 | for num in nums: 24 | eor ^= num 25 | 26 | # find first bit is 1 27 | firstBitis1 = 0 28 | while eor & 1 == 0: 29 | eor >>= 1 30 | firstBitis1 += 1 31 | 32 | judgegroup = lambda x, n: (x >> n) & 1 33 | r1, r2 = 0, 0 34 | for num in nums: 35 | if judgegroup(num, firstBitis1): 36 | r1 ^= num 37 | else: 38 | r2 ^= num 39 | 40 | return r1, r2 41 | 42 | 43 | def singleNumbers_hash(self, nums: List[int]) -> List[int]: 44 | ''' 45 | 哈希表 + 删除 70+ms 46 | ''' 47 | n_dict = dict() 48 | for num in nums: 49 | n_dict[num] = n_dict.get(num, 0) + 1 50 | if n_dict[num] == 2: 51 | del n_dict[num] 52 | return list(n_dict.keys()) 53 | 54 | if __name__ == "__main__": 55 | S = Solution() 56 | print(S.singleNumbers([1, 2, 5, 2])) -------------------------------------------------------------------------------- /05_leetcode/Offer 56.II 数组中数字出现的次数.py: -------------------------------------------------------------------------------- 1 | #! -*- encoding:utf-8 -*- 2 | """ 3 | @File : Offer 56.I 数组中数字出现的次数.py 4 | @Author : Zachary Li 5 | @Contact : li_zaaachary@163.com 6 | @Dscpt : 在一个数组 nums 中除一个数字只出现一次之外,其他数字都出现了三次。请找出那个只出现一次的数字。 7 | 8 | 输入:nums = [3,4,3,3] 9 | 输出:4 10 | """ 11 | from typing import List 12 | 13 | 14 | class Solution: 15 | def singleNumber(self, nums: List[int]) -> int: 16 | ''' 17 | time: 28.47%; memory: 80.97% 18 | 将所有数字的二进制每一位相加,如果某一位能被3整除 19 | ''' 20 | bits = [0] * 32 21 | for num in nums: 22 | bitmask = 1 23 | for i in range(31, -1, -1): 24 | if num & bitmask: 25 | bits[i] += 1 26 | bitmask <<= 1 27 | result = 0 28 | for i in range(32): 29 | result = result << 1 30 | result += bits[i]%3 31 | return result 32 | 33 | 34 | if __name__ == "__main__": 35 | S = Solution() 36 | print(S.singleNumber([3,4,3,3])) -------------------------------------------------------------------------------- /05_leetcode/Offer 62_圆圈中最后剩下的数字.py: -------------------------------------------------------------------------------- 1 | """ 2 | 0,1,...,n-1这n个数字排成一个圆圈,从数字0开始, 3 | 每次从这个圆圈里删除第m个数字。求出这个圆圈里剩下的最后一个数字。 4 | 5 | 例如,0、1、2、3、4这5个数字组成一个圆圈, 6 | 从数字0开始每次删除第3个数字,则删除的前4个数字依次是2、0、4、1,因此最后剩下的数字是3。 7 | 8 | 来源:力扣(LeetCode) 9 | 链接:https://leetcode-cn.com/problems/yuan-quan-zhong-zui-hou-sheng-xia-de-shu-zi-lcof 10 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 11 | """ 12 | 13 | class Solution: 14 | def lastRemaining(self, n: int, m: int) -> int: 15 | num_list = [i for i in range(n)] 16 | current = 0 17 | while len(num_list) > 1: 18 | current = (current + m - 1) % len(num_list) 19 | del num_list[current] 20 | # num_list.pop(current) 21 | return num_list[0] 22 | 23 | def lastRemaining2(self, n: int, m: int) -> int: 24 | """ 25 | 我们知道,从 f(n - m) 场景下删除的第一个数的序号是 (m - 1) % n, 26 | 那么 f(n - 1, m) 场景将使用被删除数字的下一个数,即序号 m % n 作为它的 0 序号。 27 | 28 | 设 f(n - 1, m) 的结果为 x,x 是从 f(n, m) 场景下序号为 m % n 的数字出发所获得的结果, 29 | 因此,我们可以得出:m % n + x 是该数字在 f (n, m) 场景下的结果序号。即: 30 | 31 | f(n, m) = m % n + x 32 | 但由于 m % n + x 可能会超过 n 的范围,所以我们再取一次模: 33 | 34 | f(n , m) = (m % n + x) % n = (m + x) % n 35 | 将 f(n - 1, m) 代回,得到递推公式: 36 | 37 | f(n, m) = (m + f(n - 1, m)) % n 38 | 有了递推公式后,想递归就递归,想迭代就迭代咯~ 39 | """ 40 | return self.f(n, m) 41 | 42 | def f(self, n, m): 43 | if n == 0: 44 | return 0 45 | x = self.f(n - 1, m) 46 | return (m + x) % n 47 | 48 | 49 | if __name__ == "__main__": 50 | s = Solution() 51 | print(s.lastRemaining(5, 3)) 52 | print(s.lastRemaining(10, 17)) 53 | -------------------------------------------------------------------------------- /05_leetcode/about-leetcode.md: -------------------------------------------------------------------------------- 1 | # about-leetcode 2 | 3 | ## 双指针 4 | - 0142, 0209, -------------------------------------------------------------------------------- /06_其他/Huawei/01字符串最后一个单词长度.py: -------------------------------------------------------------------------------- 1 | # 方法一 2 | import sys 3 | 4 | line = sys.stdin.readline().strip().split()[-1] 5 | print(len(line)) 6 | 7 | # 方法二 8 | s = input() 9 | print(len(s.split()[-1])) -------------------------------------------------------------------------------- /06_其他/Huawei/02计算字符个数.py: -------------------------------------------------------------------------------- 1 | # 写出一个程序,接受一个由字母和数字组成的字符串,和一个字符, 2 | # 然后输出输入字符串中含有该字符的个数。不区分大小写。 3 | 4 | from sys import stdin as std 5 | str1 = std.readline().strip().lower() 6 | char2 = std.readline().strip().lower() 7 | print(str1.count(char2)) 8 | -------------------------------------------------------------------------------- /06_其他/Huawei/03明明的随机数.py: -------------------------------------------------------------------------------- 1 | # N个1~1000的随机数 2 | # 对于重复数字指保留一个,去掉其他相同的数 3 | # 对这些数从小到大排序 4 | import sys 5 | 6 | s = set() 7 | lines = sys.stdin.readlines() 8 | linenum = 0 9 | result = [] 10 | while linenum < len(lines): 11 | n = int(lines[linenum].strip()) 12 | for line in lines[linenum + 1:linenum + n + 1]: 13 | s.add(int(line.strip())) 14 | result.extend(sorted(s)) 15 | s.clear() 16 | linenum += n + 1 17 | 18 | for item in result: 19 | print(item) 20 | 21 | 22 | # 注意多组数据的输入! 23 | 24 | def method2(): 25 | while True: 26 | try: 27 | n = int(input()) 28 | l = [int(input()) for _ in range(n)] 29 | l = sorted(set(l)) 30 | for i in l: 31 | print(i) 32 | except: 33 | break -------------------------------------------------------------------------------- /06_其他/PTA/1001_3n+1.py: -------------------------------------------------------------------------------- 1 | """ 2 | 对任何一个正整数 n,如果它是偶数,那么把它砍掉一半; 3 | 如果它是奇数,那么把 (3n+1) 砍掉一半。 4 | 这样一直反复砍下去,最后一定在某一步得到 n=1。 5 | 6 | 而是对给定的任一不超过 1000 的正整数 n,简单地数一下, 7 | 需要多少步(砍几下)才能得到 n=1? 8 | 输入样例 9 | 3 10 | 输出样例 11 | 3 12 | """ 13 | 14 | def count_step(n:int): 15 | step = 0 16 | while n!=1: 17 | if n%2 == 0: 18 | n = n//2 19 | else: 20 | n = (3*n +1)//2 21 | step += 1 22 | return step 23 | 24 | if __name__ == "__main__": 25 | while True: 26 | try: 27 | n = int(input()) 28 | print(count_step(n)) 29 | except: 30 | break -------------------------------------------------------------------------------- /06_其他/PTA/1005_继续3n+1.py: -------------------------------------------------------------------------------- 1 | """ 2 | 对任何一个正整数 n,如果它是偶数,那么把它砍掉一半; 3 | 如果它是奇数,那么把 (3n+1) 砍掉一半。 4 | 这样一直反复砍下去,最后一定在某一步得到 n=1。 5 | 6 | 验证卡拉兹猜想的时候,为了避免重复计算,可以记录下递推过程中遇到的每一个数。 7 | 例如对 n=3 进行验证的时候,我们需要计算 3、5、8、4、2、1, 8 | 则当我们对 n=5、8、4、2 进行验证的时候,就可以直接判定卡拉兹猜想的真伪, 9 | 我们称 5、8、4、2 是被 3“覆盖”的数。 10 | 我们称一个数列中的某个数 n 为“关键数”,如果 n 不能被数列中的其他数字所覆盖。 11 | 12 | 现在给定一系列待验证的数字,我们只需要验证其中的几个关键数, 13 | 就可以不必再重复验证余下的数字。你的任务就是找出这些关键数字, 14 | 并按从大到小的顺序输出它们。 15 | 16 | 输入: 17 | 第 1 行给出一个正整数 K (<100), 18 | 第 2 行给出 K 个互不相同的待验证的正整数 n (11有dn是偶数 4 | 素数对猜想认为存在无穷多相邻且差为2的素数 5 | 6 | 先给定任意正整数N(<10^5)请计算不超过N的满足猜想的素数对的个数 7 | 8 | 输入 9 | N 10 | 输出个数 11 | """ 12 | # import sympy 13 | import math 14 | 15 | def is_prime_fast(num): 16 | if num <= 1: 17 | return False 18 | elif num == 2 or num == 3: 19 | return True 20 | elif num % 6 in (0, 2, 3, 4): 21 | return False 22 | else: 23 | half = int(math.sqrt(num)) + 1 24 | for i in range(5, half, 6): 25 | if num % i == 0 or num % (i+2) == 0: 26 | return False 27 | else: 28 | return True 29 | 30 | def primes(max): 31 | pairs = 0 32 | prime_list = [i for i in range(1,max+1) if is_prime_fast(i)] 33 | if len(prime_list) in (0,1): 34 | print(0) 35 | else: 36 | i = 1 37 | l = prime_list[0] 38 | for i in range(1, len(prime_list)): 39 | c = prime_list[i] 40 | if c - l == 2: 41 | pairs += 1 42 | l = c 43 | print(pairs) 44 | 45 | if __name__ == "__main__": 46 | while True: 47 | try: 48 | primes(int(input())) 49 | except: 50 | break 51 | 52 | 53 | """ 54 | n = int(input()) 55 | step = 2 56 | contrast = [True] * (n + 2) 57 | result = [] 58 | 59 | while step <= n: 60 | result.append(step) 61 | for i in range(step * 2, n + 1, step): 62 | contrast[i] = False 63 | while step <= n: 64 | step += 1 65 | if contrast[step]: 66 | break 67 | 68 | print(len([i for i in range(len(result) - 1) if result[i + 1] - result[i] == 2])) 69 | """ 70 | -------------------------------------------------------------------------------- /06_其他/PTA/1009_说反话.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给定一句英语,编写程序,将句中的所有单词颠倒输出。 3 | 4 | 测试输入包含一个测试用例,在一行内给出总长度不超过 80 的字符串。 5 | 字符串由若干单词和若干空格组成,其中单词是由英文字母(大小写有区分)组成的字符串, 6 | 单词之间用 1 个空格分开,输入保证句子末尾没有多余的空格。 7 | """ 8 | 9 | if __name__ == "__main__": 10 | while True: 11 | try: 12 | eng_str = input() 13 | word_list = eng_str.split() 14 | # drow_tsil = list(map(lambda word: ''.join(reversed(word)),word_list)) 15 | word_list.reverse() 16 | print(' '.join(word_list)) 17 | except: 18 | break -------------------------------------------------------------------------------- /06_其他/PTA/1011_A+BandC.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给定[-2^31,2^31]内的三个整数,A、B、C判断A+B是否大于C 3 | 4 4 | 1 2 3 5 | 2 3 4 6 | 2147483647 0 2147483646 7 | 0 -2147483648 -2147483647 8 | 9 | Case #1: false 10 | Case #2: true 11 | Case #3: true 12 | Case #4: false 13 | 14 | """ 15 | 16 | if __name__ == "__main__": 17 | T = int(input()) 18 | case_list = [] 19 | for i in range(T): 20 | case_list.append(tuple(map(int, input().split()))) 21 | temp = 1 22 | for case in case_list: 23 | result = 'Case #'+str(temp)+': ' 24 | result += 'true' if case[0]+case[1]>case[2] else 'false' 25 | print(result) 26 | temp += 1 -------------------------------------------------------------------------------- /06_其他/PTA/1015_德才论.py: -------------------------------------------------------------------------------- 1 | """ 2 | “是故才德全尽谓之圣人,才德兼亡谓之愚人,德胜才谓之君子,才胜德谓之小人。凡取人之术,苟不得圣人,君子而与之,与其得小人,不若得愚人。” 3 | 《资治通鉴》 4 | 5 | 现给出一批考生的德才分数,请根据司马光的理论给出录取排名。 6 | 第一行 N总数;L最低分数线;H优先录取线 7 | 考生信息: 准考证号 德分 才分 8 | 9 | 德才皆高于L才可考虑录取 10 | 1双全: 德才皆高于H 按德才总分高低排序 11 | 2德胜才: 德>H 才低于H 12 | 3才德兼亡 但德胜才 H>德>才 13 | 4其余>L 14 | 15 | 当某类考生中有多人总分相同时,按其德分降序排列; 16 | 若德分也并列,则按准考证号的升序输出。 17 | """ 18 | 19 | 20 | 21 | if __name__ == "__main__": 22 | N, L, H = map(int,input().split()) 23 | stu_list1,stu_list2,stu_list3,stu_list4 = [],[],[],[] 24 | 25 | for _ in range(N): 26 | stu_id, d, c = map(int, input().split()) 27 | if d >= L or c >= L: 28 | if d >= H and c >=H: 29 | stu_list1.append((stu_id, d, c)) # 双全 30 | elif d >= H: 31 | # 德 >= H > 才 32 | stu_list2.append((stu_id, d, c)) 33 | elif d >= c: 34 | stu_list3.append((stu_id, d, c)) 35 | else: 36 | stu_list4.append((stu_id, d, c)) 37 | 38 | print(len(stu_list1)+len(stu_list2)+len(stu_list3)+len(stu_list4)) 39 | for stu_list in stu_list1,stu_list2,stu_list3,stu_list4: 40 | for stu in stu_list: 41 | # 总分的情况下再德分,学号排序 42 | stu_list.sort(key=lambda stu: (stu[1]+stu[2],stu[1],-stu[0]), reverse=True) 43 | print('{0[0]} {0[1]} {0[2]}'.format(stu)) 44 | -------------------------------------------------------------------------------- /06_其他/PTA/1017_A除以B.py: -------------------------------------------------------------------------------- 1 | """ 2 | 本题要求计算 A/B,其中 A 是不超过 1000 位的正整数,B 是 1 位正整数。 3 | 你需要输出商数 Q 和余数 R,使得 A=B×Q+R 成立。 4 | """ 5 | 6 | if __name__ == "__main__": 7 | A, B = map(int, input().split()) 8 | Q = A // B 9 | R = A % B 10 | print('{} {}'.format(Q,R)) -------------------------------------------------------------------------------- /06_其他/PTA/1019_数字黑洞.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给定任一个各位数字不完全相同的 4 位正整数, 3 | 如果我们先把 4 个数字按 非递增排序 ,(减) 4 | 再按非递减排序(增),然后用第 1 个数字减第 2 个数字,将得到一个新的数字。 5 | 6 | 一直重复这样做,我们很快会停在有“数字黑洞”之称的 6174,这个神奇的数字也叫 Kaprekar 常数。 7 | 8 | 现给定任意 4 位正整数,请编写程序演示到达黑洞的过程。 9 | """ 10 | 11 | def show_process(int_list): 12 | # ['7', '7','6','6'] 13 | while int_list != list('6174'): 14 | int_list1 = sorted(int_list,reverse=True) 15 | int_list2 = sorted(int_list) 16 | int1 = int(''.join(int_list1)) 17 | int2 = int(''.join(int_list2)) 18 | int3 = int1 - int2 19 | int_list = list(str(int3)) 20 | print('{:4d} - {:04d} = {:04d}'.format(int1, int2, int3)) 21 | 22 | 23 | if __name__ == "__main__": 24 | int_list = list(input()) 25 | if len(set(int_list)) == 1: 26 | print('{0:04d} - {0:04d} = 0000'.format(int(''.join(int_list)))) 27 | else: 28 | show_process(int_list) 29 | -------------------------------------------------------------------------------- /06_其他/PTA/1021_个位数统计.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给定一个k位整数N = dk-1 * 10^k-1 + ... + d1 * 10^1 3 | (0<=di<=9, i=0,...,k-1,dk-1>0) 4 | 编写程序统计每种不同的各位数字出现的次数 5 | 例如给N=100311则有2个03个1和1个3 6 | 7 | 每个输入包含1个测试用例,即一个不超过1000位的正整数N 8 | 对N中每一种不同的个位数字,以D:M的格式在一行中输出D及其次数M 9 | 要求按D的升序输出 10 | """ 11 | 12 | def count_num(N): 13 | num_dict = {} 14 | for ch in N: 15 | num_dict[ch] = num_dict.get(ch, 0) + 1 16 | 17 | return num_dict 18 | 19 | if __name__ == "__main__": 20 | N = input() 21 | num_dict = count_num(N) 22 | num_list = sorted(num_dict) 23 | for num in num_list: 24 | print("{}:{}".format(num, num_dict[num])) 25 | -------------------------------------------------------------------------------- /06_其他/PTA/1023_组个最小数.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给定数字 0-9 各若干个。你可以以任意顺序排列这些数字,但必须全部使用。 3 | 目标是使得最后得到的数尽可能小(注意 0 不能做首位)。 4 | 例如:给定两个 0,两个 1,三个 5,一个 8,我们得到的最小的数就是 10015558。 5 | 现给定数字,请编写程序输出能够组成的最小的数。 6 | 7 | 输入在一行中给出 10 个非负整数,顺序表示我们拥有数字 0、数字 1、……数字 9 的个数。 8 | 整数间用一个空格分隔。 9 | 10 个数字的总个数不超过 50,且至少拥有 1 个非 0 的数字。 10 | """ 11 | 12 | def f(): 13 | num_list = list(map(int, input().split())) 14 | first = 0 15 | for i in range(1, len(num_list)): 16 | if num_list[i] != 0: 17 | first = i 18 | num_list[i] -= 1 19 | break 20 | i += 1 21 | else: 22 | print('0') 23 | return 24 | print(first,end='') 25 | current = 0 26 | for num in num_list: 27 | for i in range(num): 28 | print(current, end='') 29 | current += 1 30 | 31 | if __name__ == "__main__": 32 | f() -------------------------------------------------------------------------------- /06_其他/PTA/1025_反转链表.py: -------------------------------------------------------------------------------- 1 | """ 2 | 给定一个常数 K 以及一个单链表 L,请编写程序将 L 中每 K 个结点反转。 3 | 例如:给定 L 为 1→2→3→4→5→6,K 为 3,则输出应该为 3→2→1→6→5→4; 4 | 如果 K 为 4,则输出应该为 4→3→2→1→5→6,即最后不到 K 个元素不反转。 5 | 6 | 第一行 结点1地址 结点总个数 反转的子链个数 7 | 8 | 两个测试点报错 9 | """ 10 | 11 | 12 | 13 | 14 | if __name__ == "__main__": 15 | firstadd, total, relength = map(int, input().split()) 16 | 17 | # 生成链表 18 | d = dict() 19 | for i in range(total): 20 | add, data, next = map(int, input().split()) 21 | d[add] = [data, next] 22 | 23 | # 反转 24 | d[-2] = [0, firstadd] # 假头 25 | current, privchain = firstadd, -2 26 | priv = -2 27 | for _ in range(int(total//relength)): 28 | for _ in range(relength): 29 | next = d[current][1] 30 | d[current][1] = priv 31 | priv = current 32 | current = next 33 | temp = d[privchain][1] 34 | d[temp][1] = current 35 | d[privchain][1] = priv 36 | privchain = priv = temp 37 | 38 | # 输出 39 | next = d[-2][1] 40 | while next!=-1: 41 | if d[next][1] != -1: 42 | print('{0:05} {1[0]} {1[1]:05}'.format(next, d[next])) 43 | else: 44 | print('{0:05} {1[0]} {1[1]}'.format(next, d[next])) 45 | next = d[next][1] -------------------------------------------------------------------------------- /06_其他/PTA/1027_打印沙漏.py: -------------------------------------------------------------------------------- 1 | """ 2 | 两个测试点通过,两个测试点格式错误 3 | """ 4 | 5 | def num2level(num): 6 | # 给定num返回 上半层最多一层的符号个数 7 | if num == 1: 8 | return 1, 0 9 | num, mod = divmod((num - 1), 2) # 上半部分的符号个数 10 | num += 1 11 | temp = 1 12 | while temp <= num: 13 | num -= temp 14 | temp += 2 15 | return temp-2, mod + num*2 16 | 17 | def printgraph(long, ch): 18 | for i in range(long,-1,-2): 19 | print((ch*i).center(long,' ')) 20 | for i in range(3, long+1, 2): 21 | print((ch*i).center(long, ' ')) 22 | 23 | if __name__ == "__main__": 24 | N, ch = input().split() 25 | N = int(N) 26 | temp,left = num2level(N) 27 | printgraph(temp, ch) 28 | print(left, end='') -------------------------------------------------------------------------------- /06_其他/feibo.py: -------------------------------------------------------------------------------- 1 | """ 2 | 测试 3 | """ 4 | 5 | class fb: 6 | num_list = [] 7 | def __init__(self): 8 | self.num_list.extend(1, 1) 9 | 10 | def __str__(self): 11 | return self.num_list 12 | 13 | 14 | def f1(n): 15 | # 递归法 16 | a, b = 1,1 17 | if n > 2: 18 | for _ in range(2, n): 19 | a, b = b, a+b 20 | return b 21 | 22 | 23 | def f2(): 24 | # 生成器 25 | a, b = 1, 1 26 | while True: 27 | yield a 28 | a, b = b, a+b 29 | 30 | if __name__ == "__main__": 31 | a = f2() 32 | for i in range(10): 33 | print(a.__next__(), end=',') 34 | 35 | print(f1(10)) 36 | -------------------------------------------------------------------------------- /06_其他/原地删除重复.py: -------------------------------------------------------------------------------- 1 | """ 2 | 如何在没有函数返回值的情况下, 原地删除列表中重复的元素 3 | """ 4 | from collections import Counter 5 | 6 | 7 | def setmethod(L): 8 | temp_set = set(L) 9 | L.clear() 10 | L.extend(list(temp_set)) 11 | 12 | 13 | def setmethod2(L): 14 | # 不改变顺序 15 | t = sorted(set(L), key=L.index) 16 | L.clear() 17 | L.extend(t) 18 | 19 | 20 | def popmethod(L): 21 | freq_dict = Counter(L) 22 | for index in range(len(L)-1, -1, -1): 23 | if freq_dict[L[index]] != 1: 24 | freq_dict[L[index]] -= 1 25 | L.pop(index) 26 | 27 | 28 | def sortoddeven(L): 29 | # L.sort(reverse=True) 30 | # L.sort(key=lambda x: 1 if x % 2 == 0 else 0) 31 | L.sort(key=lambda x: (0 if x % 2 == 0 else 1, x), reverse=True) 32 | 33 | 34 | 35 | if __name__ == "__main__": 36 | # L = [3, 2, 1, 4, 2, 5, 6, 3] 37 | # setmethod2(L) 38 | # print(L) 39 | # L = [3, 2, 1, 4, 2, 5, 6, 3] 40 | # popmethod(L) 41 | # print(L) 42 | 43 | L = [1, 2, 3, 4, 5, 6] 44 | sortoddeven(L) 45 | print(L) -------------------------------------------------------------------------------- /06_其他/简易程序/Typora/TyporaPiture.py: -------------------------------------------------------------------------------- 1 | """ 2 | 通常 typora 的图片都存储于和 .md 文件相同的目录下的图片目录里 3 | 当然也不排除 .md 文件中有的图片不在上述文件夹中 4 | 此外 在文件编辑的过程中存在粘贴了某张图片 最后却不用该图片的情况 5 | 这种情况 就会是的上述文件夹里出现无用的图片 6 | 7 | 此程序正是用来应对 typora 的图片存储问题 程序主要实现了以下功能 8 | 1. 将目标目录中的 .md 中存于 其他目录的图片 复制到 目标目录下的图片目录 9 | 2. 清理目标目录下的图片目录 删除 .md 文件未使用的图片 10 | 11 | 3. 重命名某个 .md 文件的图片名称,并更改 md 内的链接 12 | """ 13 | import os 14 | import sys 15 | import re 16 | import argparse 17 | 18 | class Cleaner: 19 | 20 | def __init__(self, targetdir='./'): 21 | self.targetdir = targetdir 22 | os.chdir(targetdir) 23 | print('Now working at ' + os.getcwd()) 24 | 25 | self.current_picture = list() 26 | 27 | def changedir(self, targetdir): 28 | print("Changing working directory") 29 | self.__init__(targetdir) 30 | 31 | def get_pic_names(self): 32 | # self.current_picture.append() 33 | pass 34 | 35 | def walk_through(self): 36 | w = os.walk(self.targetdir) 37 | for a,b,c in w: 38 | self.get_pic_names() 39 | # TO-DO 40 | self.current_picture.clear() 41 | 42 | 43 | 44 | 45 | 46 | if __name__ == "__main__": 47 | pass -------------------------------------------------------------------------------- /06_其他/简易程序/temp.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | floder = './weight/' 4 | 5 | weightbias = {} 6 | for key, value in model_params.items(): 7 | # print(key, value) 8 | if 'weight' in key or 'bias' in key: 9 | weightbias[key] = value.cpu().numpy() 10 | 11 | # print(weightbias) 12 | for key, value in weightbias.items(): 13 | print(key, value.size) 14 | np.savetxt(floder+key+'.txt', value) 15 | -------------------------------------------------------------------------------- /06_其他/简易程序/力扣题重命名.py: -------------------------------------------------------------------------------- 1 | """ 2 | Leetcode 文件夹中的文件序号 在小于4位数的序号前面补零 3 | 4 | """ 5 | import os 6 | import re 7 | 8 | class FileRenamer: 9 | def __init__(self, targetdir='./'): 10 | self.targetdir = targetdir 11 | os.chdir(targetdir) 12 | print('Now working at ' + os.getcwd()) 13 | 14 | def changedir(self, targetdir): 15 | print("Changing working directory") 16 | self.__init__(targetdir) 17 | 18 | def renamenumber(self, length): 19 | """ 20 | length: 目标数字序号长度 21 | """ 22 | pattern = re.compile(r'^\d+') 23 | # pattern = re.compile(r'^\d+_') 24 | for filename in os.listdir(): 25 | # if number := pattern.match(filename): # 海象运算符 26 | number = pattern.match(filename) 27 | if number: 28 | number = number.group() 29 | else: 30 | continue 31 | 32 | characters = filename[len(number):] 33 | num = str(int(number)) 34 | # num = int(number[:-1]) 35 | # number = str(num).rjust(length, '0') 36 | # number = str(num).rjust(length, '0')+'.' 37 | dst = num + characters 38 | print(dst) 39 | os.rename(src=filename, dst=dst) 40 | print("改名完成") 41 | 42 | if __name__ == "__main__": 43 | F = FileRenamer() 44 | # F.changedir('./06_其他') 45 | F.changedir('./05_leetcode') 46 | F.renamenumber(4) -------------------------------------------------------------------------------- /06_其他/算法/change_making.py: -------------------------------------------------------------------------------- 1 | #! -*- encoding:utf-8 -*- 2 | """ 3 | @File : change_making.py 4 | @Author : Zachary Li 5 | @Contact : li_zaaachary@163.com 6 | @Dscpt : 找零问题 7 | """ 8 | 9 | def change(money, deno): 10 | # deno: 面额列表; money: 要找零的总金额 11 | deno.sort(reverse=True) 12 | result = [] 13 | current = 0 14 | 15 | while money != current: 16 | for x in deno: 17 | if current + x <= money: 18 | result.append(x) 19 | current += x 20 | break 21 | else: 22 | return None # no solution found 23 | return result 24 | 25 | 26 | if __name__ == "__main__": 27 | denomination = [100,25,10,5,1] 28 | money = 378 29 | 30 | print(change(money, denomination)) 31 | 32 | 33 | -------------------------------------------------------------------------------- /06_其他/算法/fractional_backpack.py: -------------------------------------------------------------------------------- 1 | #! -*- encoding:utf-8 -*- 2 | """ 3 | @File : fractional_backpack.py 4 | @Author : Zachary Li 5 | @Contact : li_zaaachary@163.com 6 | @Dscpt : https://blog.csdn.net/cPen_web/article/details/111873620 7 | """ 8 | 9 | def fractional_backpack(goods, w): # 参数 商品、w背包重量 10 | # 贪心拿商品,拿单位重量更值钱的商品,所以先对goods进行排序 11 | goods.sort(key=lambda x: x[0] / x[1], reverse=True) # 按照单位价格降序排列 12 | m = [0 for _ in range(len(goods))] # m表示每个商品拿多少,存结果的 13 | total_v =0 # 存结果的 拿走的总价值 14 | for i, (price,weight) in enumerate(goods): 15 | if w >= weight: 16 | m[i] = 1 # 这个商品拿多少。拿1整个,或者小数 17 | total_v += price # 更新拿走的 价值 18 | w -= weight # 并更新w的值 (背包重量) 19 | else: 20 | m[i] = w / weight 21 | total_v += m[i] * price # 更新拿走的 价值 22 | w = 0 # 背包满了 23 | break 24 | return total_v, m # 最后返回 存结果的m、total_v 25 | 26 | if __name__ == "__main__": 27 | goods = [(60, 10), (100, 20), (120, 30)] # 每个商品元组表示 (价格,重量) 28 | print(fractional_backpack(goods, 50)) 29 | #结果为 30 | # (240.0, [1, 1, 0.6666666666666666]) 31 | -------------------------------------------------------------------------------- /06_其他/算法/permutation.py: -------------------------------------------------------------------------------- 1 | #! -*- encoding:utf-8 -*- 2 | """ 3 | @File : permutation.py 4 | @Author : Zachary Li 5 | @Contact : li_zaaachary@163.com 6 | @Dscpt : Recursion 就地生成 n 个元素的全排列 7 | """ 8 | 9 | def permute(A:list, n:int): 10 | if n == 0: 11 | print(A) 12 | else: 13 | permute(A, n-1) 14 | for i in range(n-1, -1, -1): 15 | A[i], A[n] = A[n], A[i] 16 | permute(A, n-1) 17 | A[i], A[n] = A[n], A[i] 18 | 19 | 20 | if __name__ == "__main__": 21 | permute([1,2,3], 2) -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Python-Foundation 2 | Python语言基础; suda 复试; Soochow University Python 3 | 4 | [TOC] 5 | 6 | ## 01 董付国Python 7 | 文件夹01:紫色的复试参考书目上的习题。 8 | 9 | 阅读该书时记录的笔记: 10 | [学习笔记(上)](http://nav.zrawberry.com/article/article-content/16/Python-Xue-Xi-Bi-Ji-Shang/) 11 | [学习笔记(下)](http://nav.zrawberry.com/article/article-content/22/Python-Xue-Xi-Bi-Ji-Xia/) 12 | 13 | ## 02 苏大MOOC习题 14 | 文件夹02:MOOC上的习题和考试代码 15 | 16 | 苏大MOOC [Python程序设计](https://www.icourse163.org/learn/SUDA-1206947804) 17 | 18 | 苏大MOOC 课件+单元测试 [下载](http://cloud.zrawberry.com/index.php/s/94LaJ6CTf8xK2kD) 19 | 20 | ## 03 苏大本科习题 21 | 文件夹03:期中,期末试卷 22 | 23 | 苏大本科Python课件 [下载](http://cloud.zrawberry.com/index.php/s/JJTmEH4JsNy6RBe) 24 | 25 | 苏大网络题库 [链接](http://sit.suda.edu.cn/) (选择填空判断) 26 | 27 | 刷题过程中总结笔记 [链接](http://nav.zrawberry.com/article/article-content/26/Python-Shua-Ti-Bi-Ji/) 28 | 29 | ## 04 历年复试真题 (已加入2021) 30 | 31 | 文件夹04:历年复试上机真题的C和Python实现 32 | 33 | 分享一下我朋友的资料 34 | 35 | 讲解视频:[豆子](https://www.bilibili.com/video/BV1JC4y1p7t9/) 36 | 37 | 复试习题仓库2:[豆子的苏大复试仓库](https://github.com/douzujun/Python-Foundation-Suda) 38 | 39 | ## 05 Leetcode 40 | 文件夹05:力扣刷题。 (简单为主,中等用于提升) 41 | 42 | 为什么要刷力扣? MOOC老师的原话↓ 43 | 44 | ![MOOC讨论区图](http://nav.zrawberry.com/media/picture/a049c8a39b39412cb2ecfe7e39f59165.png) 45 | 46 | ## 写在最后 47 | 欢迎大家对这个仓库进行补充! 48 | 49 | 分享一下我的Python交流群:816306317 50 | 51 | ![Python群二维码](http://nav.zrawberry.com/media/picture/38dcf43696224e6a8d3002dcb98a3302.png) 52 | --------------------------------------------------------------------------------