- 博客(1804)
- 资源 (10)
- 收藏
- 关注
原创 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
667
2
原创 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
599
原创 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
571
原创 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
239
原创 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
180
原创 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
204
原创 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
220
原创 Python for Linux and Unix System Administration -4 Reusing Code with the Import Statement
wes@wes:~/Documents/python/ch1$ cat new_pysysinfo.py#!/usr/bin/env python#Very short script that reuses pysysinfo_func codefrom pysysinfo_func import disk_funcimport subprocessdef tmp_space(): tmp_usage = "du" tmp_arg = "-h" .
2022-05-23 15:33:58
236
原创 Python for Linux and Unix System Administration -3 function
wes@wes:~/Documents/python/ch1$ cat python-5#!/usr/bin/env pythondef pyfunc(): print("Hello Function!")for i in range(5): pyfunc()wes@wes:~/Documents/python/ch1$ python python-5Hello Function!Hello Function!Hello Function!Hello Fu.
2022-05-23 14:26:17
287
原创 Python for Linux and Unix System Administration -2 subprocess
Subprocess modulesubprocess — Subprocess management — Python 3.10.4 documentationpython subprocess - Python Tutorialwes@wes:~/Documents/python/ch1$ cat python-3#!/usr/bin/env pythonimport subprocesssubprocess.call(["ls", "-l"])subprocess.call([.
2022-05-22 17:33:07
291
原创 Python for Linux and Unix System Administration -1 ping
#!/usr/bin/env pythonclass Server(object): def __init__(self,ip,hostname): self.ip = ip self.hostname = hostname def set_ip(self,ip): self.ip = ip def set_hostname(self,hostname): self.hostname = hostname .
2022-05-22 09:45:12
346
原创 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
462
原创 骑士周游问题
#合法走棋位置函数 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
313
原创 词梯游戏 广度优先算法
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
4358
原创 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
370
原创 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
1415
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
267
原创 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
524
原创 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
590
原创 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
253
原创 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
886
原创 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
258
原创 欧几里得证明
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
306
原创 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
507
原创 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
168
原创 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
207
原创 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
538
原创 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
665
原创 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
723
原创 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
265
原创 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
165
原创 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
827
原创 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
290
转载 博物馆大盗问题
大盗潜入博物馆,面前有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
249
转载 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
543
原创 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
1692
原创 python 迷宫问题
迷宫问题具体的问题是,将海龟放在迷宫中间,如下图设计一段程序,让海龟自动找到迷宫出口。首先我们将整个迷宫的空间(矩形)分为行列整齐的风格,区分出墙壁和通道。给每个方格具有行列位置,并赋予墙壁、通道等属性。考虑用矩阵方式来实现迷宫数据结构。采用“数据项为字符列表的列表”这种两级列表的方式来保存方格内容,采用不同字符来分别代表迷宫内的不同事物,如"+"代表墙壁、" "(即空格符)代表通道 ,"S"代表“海龟投放点”,从一个文本文件逐行读入迷宫数据。读入数据文件成功以后,就可以用嵌
2022-04-21 08:39:28
1257
原创 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
567
原创 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
369
1.Python基础_1.4_条件判断及循环语句.ipynb
2019-09-02
空空如也
TA创建的收藏夹 TA关注的收藏夹
TA关注的人