Python高级编程
道法自然
-西西弗斯
这个作者很懒,什么都没留下…
展开
-
OOP - corouting
def tally(): score = 0 while True: increment = yield score score += incrementif __name__=="__main__": white_sox = tally() blue_jays = tally() print(next(white_sox)) print(next(blue_jays)) print(white_sox.send(.原创 2022-05-31 17:57:47 · 484 阅读 · 3 评论 -
OOP - Generator expression(log processing)
# log_loop.pyimport sysinname = sys.argv[1]outname = sys.argv[2]with open(inname) as infile: with open(outname, "w") as outfile: warnings = (l for l in infile if "WARNING" in l) for l in warnings: outfile.write(l)...原创 2022-05-29 13:23:55 · 433 阅读 · 0 评论 -
OOP - set and dictionary comprehensions
from collections import namedtupleBook = namedtuple("Book", "author title genre")books = [ Book("Pratchett", "Nightwatch", "fantasy"), Book("Pratchett", "Thief Of Time", "fantasy"), Book("Le Guin", "The Dispossessed", "scifi"), Book("Le.原创 2022-05-29 12:34:59 · 397 阅读 · 0 评论 -
OOP- List comprehensions
input_strings = ['1', '5' ,'28', '131', '3']output_strings = []for num in input_strings: output_strings.append(int(num))print(output_strings) >>[1, 5, 28, 131, 3]input_strings = ['1', '5' ,'28', '131', '3']output_strings = [int(num.原创 2022-05-29 09:56:13 · 169 阅读 · 0 评论 -
OOP - Iterator
class CapitalIterable: def __init__(self, string): self.string = string def __iter__(self): return CapitalIterator(self.string)class CapitalIterator: def __init__(self, string): self.words = [w.capitalize() for w in.原创 2022-05-29 08:48:22 · 131 阅读 · 0 评论 -
OOP - Regular expression
re — Regular expression operations — Python 3.10.4 documentationimport research_string = "hello world"pattern = "hello world"match = re.match(pattern,search_string)if match: print("regex matches")>>regex matcheswes@wes:~/Document.原创 2022-05-26 09:14:46 · 148 阅读 · 0 评论 -
OOP - Srings and Serilizaiotn
1. String formatingtemplate = "Hello {}, you are currently {}."print(template.format('Dusty','writing'))>>Hello Dusty, you are currently writing.template = "Hello {0}, you are {1}. Your name is {0}."print(template.format('Dusty','writing')原创 2022-05-24 16:24:50 · 167 阅读 · 0 评论 -
python递归
def listSum(numList): theSum = 0 for i in numList: theSum += i return theSumnumList = [1,3,5,7,9]print(listSum(numList))>> 25theSum = (1 + (3 + (5 + (7 + 9))))theSum = (1 + (3 + (5 + 16)))theSum = (1 + (3 + 21))theSum =.原创 2022-05-20 19:03:09 · 394 阅读 · 0 评论 -
骑士周游问题
#合法走棋位置函数 def getLegalMoves(x,y,bdSize):#x,y为骑士位置,bdSize为棋盘大小 newMoves=[] moveOffsets=[(-1,-2),(-1,2),(-2,-1),(-2,1),(1,-2),(1,2),(2,-1),(2,1)]#马走日8个格子 for i in moveOffsets: newX=x+i[0] newY=y+i[1] if legalCoord(newX,b.原创 2022-05-20 15:03:50 · 246 阅读 · 0 评论 -
词梯游戏 广度优先算法
from pythonds.graphs import Graphdef buildGraph(wordFile): d = {} g = Graph() wfile = open(wordFile, 'r') #创建词桶 for line in wfile: word = line[:1] for i in range(len(word)): bucket = word[:1] + '_' + word[i.原创 2022-05-20 08:58:15 · 1893 阅读 · 0 评论 -
python 图的实现
class Vertex: def __init__(self,key): self.id = key self.connectedTo = {} def addNeighbor(self,nbr,weight=0): self.connectedTo[nbr] = weight def __str__(self): return str(self.id) + ' connectedTo: ' + str([x.i.原创 2022-05-18 07:57:15 · 307 阅读 · 0 评论 -
Python数据结构与算法分析第2版 - 第2章习题
#2.1 设计一个实验,证明列表的索引操作为常数阶。from timeit import Timerimport randomimport numpy as npfrom matplotlib import pyplot as plta = []b = []# 要证明这一点,需要看看两个操作在各个列表长度下的性能popzero = Timer("x[200]","from __main__ import x")# 测x[200]这个代码性能# "from __main__ impor原创 2022-05-17 19:53:41 · 1306 阅读 · 1 评论 -
异序词检测
def anagramSolution1_2(s1,s2): list_1 = list(s1) list_2 = list(s2) for i in range(len(list_1)): print("From s1:") print(list_1[i]) print("go to S2:") for j in range(len(list_2)): print(list_2[j]) .原创 2022-05-17 16:42:41 · 215 阅读 · 0 评论 -
Python数据结构与算法分析第2版 - 第1章习题(15) - 数独游戏
import numpy as npsudoku = np.array([ [0,5,0,0,6,1,0,0,0], [0,1,4,0,3,8,0,0,6], [6,0,0,0,0,0,7,5,1], [8,0,2,0,0,7,3,0,0], [4,0,0,0,2,0,0,0,5], [0,0,0,4,8,0,0,7,0], [0,0,6,3,0,0,1,0,0], [0,7,1,0,0,0,9,0,0], [0,0,0,6,0,9.原创 2022-05-15 15:25:13 · 451 阅读 · 0 评论 -
Python数据结构与算法分析第2版 - 第1章习题(14) - 金钩钓鱼游戏
# 金钩钓鱼扑克牌import randomimport timedef cards_init(): source_cards = [['A',4],['2',4],['3',4],['4',4],['5',4],['6',4],['7',4],['8',4],['9',4], ['10',4],['J',4],['Q',4],['K',4],] #除去大小王的扑克牌, 4表示每个面值有4张 player_1 = [] # 抓牌前玩家pl.原创 2022-05-15 13:50:36 · 514 阅读 · 0 评论 -
Python-for-Unix-and-Linux-System-Administration: Note for the book “Python for Unix
GitHub - paulxu/Python-for-Unix-and-Linux-System-Administration: Note for the book "Python for Unix and Linux System Administration"原创 2022-05-11 23:09:43 · 196 阅读 · 0 评论 -
python for linux system administrator tuitor
IBM Developer原创 2022-05-11 20:44:22 · 189 阅读 · 0 评论 -
Python数据结构与算法分析第2版 - 第1章习题(1-13)
目录1. 实现简单的方法getNum 和getDen ,它们分别返回分数的分子和分母。分子numeratorand分母denominator2. 如果所有分数从一开始就是最简形式会更好。修改Fraction 类的构造方法,立即使用最大公因数来化简分数。注意,这意味着__add__不再需要化简结果。(在初始化过程中就化简)3. 实现下列简单的算术运算:sub、mul和__truediv__ 。4.实现下列关系运算:gt、ge、lt、le和__ne__ 。1....原创 2022-05-11 18:18:38 · 797 阅读 · 0 评论 -
python用类实现逻辑电路
class LogicGate: def __init__(self, n): self.label = n self.output = None def getLael(self): return self.label def getOutput(self): self.output = self.performGateLogic() # 该方法并未定义,在创建子类的时候定义 return s.原创 2022-05-10 22:11:34 · 213 阅读 · 0 评论 -
欧几里得证明
15岁女孩参加世界顶尖科学家大会!她研究的贝祖数是什么?_哔哩哔哩_bilibili求104与40的最大公约数:画长为104,宽为40的矩形,能不能找到一个正方形,用正方形可以完整的一点不落的把这个长方形填满。最大的正方形的边长就是104与40的最大公约数。填充2个边长为40的正方形,剩下的边长为104 -40 - 40 = 24. 余下的空间为 24 x 40 的区域余下的空间填充边长为24的正方形,于是剩下的宽度为 40 - 24 = 16,即 24 x 16的区域.原创 2022-05-10 19:25:53 · 270 阅读 · 0 评论 -
python shortcuts
Placing it in contextimport random, stringclass StringJoiner(list): def __enter__(self): return self def __exit__(self,type,value,tb): self.result = "".join(self)with StringJoiner() as joiner: for i in range(15):原创 2022-05-10 14:25:03 · 441 阅读 · 0 评论 -
python 二分查找树
class BinarySearchTree: def __init__(self): # 定义根节点 self.root = None # 用于记录树的大小,即树中有多少个node self.size = 0 def put(self,key,val): # 新node加入树中 if self.root: self._put(key,val,self.root) .原创 2022-05-09 17:21:29 · 134 阅读 · 0 评论 -
python 二叉堆的实现
Python数据结构——二叉堆的实现 - 知乎class BinHeap: def __init__(self): self.heapList = [0] self.currentSize = 0 def percUp(self,i): while i // 2 > 0: if self.heapList[i] < self.heapList[i // 2]: tmp = s.原创 2022-05-08 16:33:25 · 175 阅读 · 0 评论 -
python - tuple, set, dictionary
# Using dictionariesstocks = { "GOOG": (1235.20, 1242.54, 1231.06), "MSFT": (110.41, 110.45, 109.84),}random_keys = {}random_keys["astring"] = "somestring"random_keys[5] = "aninteger"random_keys[25.2] = "floats work too"random_keys[("abc",.原创 2022-05-07 14:44:57 · 512 阅读 · 0 评论 -
python二叉树实现 - 树的遍历
from pythonds.trees import BinaryTreeimport operatordef preorder(self): print(self.key) if self.leftChild: self.left.preorder() if self.rightChild: self.right.preorder()def postorder(tree): if tree != None: pos.原创 2022-05-07 11:26:24 · 632 阅读 · 0 评论 -
python二叉树实现 - 解析树构造器
from pythonds.basic import Stackfrom pythonds.trees import BinaryTreedef buiildParseTree(fpexp): fplist = fpexp.split() pStack = Stack() eTree = BinaryTree('') pStack.push(eTree) currentTree = eTree for i in fplist: if i.原创 2022-05-05 19:35:41 · 679 阅读 · 0 评论 -
python二叉树实现 - 嵌套实现与链表实现
# nested designdef BinaryTree(r): return[r,[],[]]def insertLeft(root,newBranch): t = root.pop(1) if len(t)>1: root.insert(1,[newBranch,t,[]]) else: root.insert(1,[newBranch,[],[]]) return root def insert.原创 2022-05-03 14:43:13 · 226 阅读 · 0 评论 -
Python 3面向对象编程(第3版)第四章- 异常处理代码
#Auth.pyimport hashlibclass AuthException(Exception): def __init__(self, username, user=None): super().__init__(username, user) self.username = username self.user = userclass UsernameAlreadyExists(AuthException): pa.原创 2022-05-03 10:22:36 · 138 阅读 · 0 评论 -
Python 3面向对象编程(第3版)GITHUB源码
GitHub - PacktPublishing/Python-3-Object-Oriented-Programming-Third-Edition: Python 3 Object-Oriented Programming – Third Edition, published by Packt原创 2022-05-01 11:46:29 · 767 阅读 · 0 评论 -
Python 3面向对象编程(第2版)- Chapter2 Case Study
Test1>>> notebook.pyimport datetime# Store the next available id for all new noteslast_id = 0class Note: '''Represent a note in the notebook. Match against a sring in searches and store tage for each note.''' def __init__.原创 2022-05-01 09:50:03 · 257 阅读 · 0 评论 -
博物馆大盗问题
大盗潜入博物馆,面前有5件不同的宝物,每件宝物都分别有自己的重量和价值。大盗的背包仅能负重20KG,请问如何选择某几件宝物,使得总价值最高?宝物item 重量weight 价值value 1 2 3 2 3 4 3 4 8 4 5 8 5 9 10分析:贪心策转载 2022-04-26 14:22:16 · 200 阅读 · 0 评论 -
python 货币找零
Python数据结构与算法35:找零兑换问题的动态规划解法 - 简书# 找零兑换:动态规划算法v1。def dpMakeChange(coinValueList, change, minCoins): # 从1分钱开始到change逐个计算最小硬币数。 for cents in range(1, change + 1): # 1. 初始化一个最大值。 coinCount = cents # 2. 减去每个硬币,向后查最少硬币数,同时记录转载 2022-04-26 13:46:52 · 489 阅读 · 0 评论 -
python 货币找零
贪心算法value = [1, 5, 10, 25] #零钱分类ans = [0] * len(value) #根据硬币种类创建数组print(ans)n = len(value)money = int(input())for j in range(0,n): i = n - j - 1 # 从最大金额开始(j从0开始,i=n-j-1 刚还对应value[i]最后一个元素,即最大面额的货币) ans[i] = money // value[i] #用面值最原创 2022-04-21 19:16:02 · 1570 阅读 · 0 评论 -
python 迷宫问题
迷宫问题具体的问题是,将海龟放在迷宫中间,如下图设计一段程序,让海龟自动找到迷宫出口。首先我们将整个迷宫的空间(矩形)分为行列整齐的风格,区分出墙壁和通道。给每个方格具有行列位置,并赋予墙壁、通道等属性。考虑用矩阵方式来实现迷宫数据结构。采用“数据项为字符列表的列表”这种两级列表的方式来保存方格内容,采用不同字符来分别代表迷宫内的不同事物,如"+"代表墙壁、" "(即空格符)代表通道 ,"S"代表“海龟投放点”,从一个文本文件逐行读入迷宫数据。读入数据文件成功以后,就可以用嵌原创 2022-04-21 08:39:28 · 1168 阅读 · 0 评论 -
python 汉诺塔
def movTower(height, fromPole, withPole, toPole): if height >= 1: movTower(height - 1, fromPole, toPole, withPole) movDisk(height, fromPole, toPole) movTower(height - 1, withPole, fromPole, toPole) def movDisk(disk,.原创 2022-04-20 23:10:18 · 537 阅读 · 0 评论 -
python Queue
class Queue: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def enqueue(self,item): self.items.insert(0,item) def dequeue(self): return self.items.pop() .原创 2022-04-18 08:44:50 · 340 阅读 · 0 评论 -
面向对象学习笔记19 异常处理/Assertion
基本语法:# 如果try下面的代码出错则执行except下面的代码,如果没出错则继续执行else下面代码,不管出错没出错都执行finally下面代码try: passexcept Exception as err:#将错误信息封装到err中 # 输出错误信息 print(err)else: passfinally: pass主动触发异常try: # 主动触发异常 raise Exception('主动错误一下') # e原创 2022-04-17 09:20:05 · 211 阅读 · 0 评论 -
面向对象学习笔记18 动态创建类和isinstance和issubclass方法
# 给动态生产的类定义一个方法def __init__(self,name): self.name = name print(self.name)def take(self,obj): print(obj)# 动态生成一个类type('类名',(父类1,父类2,),{字典:属性或方法})Dog = type('Dog',(object,),{'age':22,'__init__':__init__,'take':take})d = Dog('wdc')d....原创 2022-04-17 08:27:03 · 267 阅读 · 0 评论 -
面向对象学习笔记17 类的双下划线方法
python_面向对象——双下划线方法 - 手可摘星辰。 - 博客园1.__str__和__repe__class Person(object): def __init__(self,name,age): self.name = name self.age = age def __str__(self): return 'stf:我叫{},今年{}岁'.format(self.name,self.age) def __.原创 2022-04-16 21:47:14 · 389 阅读 · 0 评论 -
Python Stack
十进制转任意进制import pythondsfrom pythonds.basic import Stackdef baseConverter(decNumber,base): digits = "0123456789ABCDEF" remstack = Stack() while decNumber >= 0: rem = decNumber % base remstack.push(rem) decNu原创 2022-04-15 18:19:59 · 244 阅读 · 0 评论