1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > Python数据结构与算法分析(第二版)答案 - 第一章(未完)

Python数据结构与算法分析(第二版)答案 - 第一章(未完)

时间:2020-11-18 16:10:09

相关推荐

Python数据结构与算法分析(第二版)答案 - 第一章(未完)

本人手写或借阅资料,仅供参考,有错误欢迎指正。

#1.1 Fraction(分数)的getNum()以及getDen()

#1.2 所有分数一开始就是最简形式

#1.3 实现下列简单的算术运算:__sub__、__mul__和__truediv__

#1.4 实现下列关系运算:__gt__、__ge__、__lt__、__le__和__ne__

#1.5 修改Fraction 类的构造方法,使其检查并确保分子和分母均为整数。如果任一不是整数,就抛出异常

#1.6 对于负数分母,gcd已实现,熟悉对负数取余

#1.7 __radd__方法:在加法的右边,对于a + b来说:

#如果 a 有 __add__ 方法, 而且返回值不是 NotImplemented, 调用a.__add__(b), 然后返回结果。

#如果 a 没有 __add__ 方法, 或者调用 __add__ 方法返回NotImplemented, 检查 b 有没有 __radd__ 方法,

#如果有, 而且没有返回 NotImplemented, 调用 b.__radd__(a), 然后返回结果。

#如果 b 没有 __radd__ 方法, 或者调用 __radd__ 方法返回NotImplemented, 抛出 TypeError, 并在错误消息中指明操作数类型不支持。

#在python3中,像 __radd__, __rmul__ 等被重载的运算符,在满足下面两种情况下才会被调用

#两个操作数类型不同

#左边的操作数没有实现__add__方法或 __add__ 返回 NotImplemented

#1.8 __iadd__方法是运算符类operator的成员函数,就是累加操作符的另一种调用形式。a = operator.__iadd__(a, b)就等价于a += b

#1.9 __repr__方法,str出来的值是给人看的字符串,repr出来的值是给机器看的,括号中的任何内容出来后都是在它之上再加上一层引号。

def gcd(m, n):while m % n != 0:oldm = moldn = nm = oldnn = oldm % oldnreturn nclass Fraction():def __init__(self, top, bottom):if type(top) != int or type(bottom) != int:raise RuntimeError('not int var inputed')self.num = topself.den = bottomcommon = gcd(self.num, self.den)self.num //= commonself.den //= commonprint(self.num,self.den)def getNum(self):return self.numdef getDen(self):return self.dendef show(self):print(self.num, '/', self.den)def __str__(self):return str(self.num) + '/' + str(self.den)def __add__(self, other):newden = self.den * other.dennewnum = self.den * other.num + other.den * self.numreturn Fraction(newnum, newden)def __radd__(self, other):newden = self.den * other.dennewnum = self.den * other.num + other.den * self.numreturn Fraction(newnum, newden)def __sub__(self, other):newden = self.den * other.dennewnum = other.den * self.num - self.den * other.numreturn Fraction(newnum, newden)def __mul__(self, other):newden = self.den * other.dennewnum = self.num * other.numreturn Fraction(newnum, newden)def __truediv__(self, other):newden = self.den * other.numnewnum = self.num * other.denreturn Fraction(newnum, newden)def __eq__(self, other):return self.num * other.den == self.den * other.numdef __gt__(self, other):return self.num * other.den > self.den * other.numdef __ge__(self, other):return self.num * other.den >= self.den * other.numdef __le__(self, other):return self.num * other.den <= self.den * other.numdef __lt__(self, other):return self.num * other.den < self.den * other.numdef __ne__(self, other):return self.num * other.den != self.den * other.numdef fractiontest():myfraction1 = Fraction(1, -1)myfraction2 = Fraction(1, -2)print(myfraction1 + myfraction2)

#1.10 研究其他类型的逻辑门(例如与非门、或非门、异或门)。将它们加入电路的继承层次结构

#门的基类

class LogicGate():def __init__(self, n):self.label = nself.output = Nonedef getlabel(self):return self.labeldef getoutput(self):self.output = self.performanceGateLogic()return self.output#双引脚门class BinaryGate(LogicGate):def __init__(self, n):super().__init__(n)self.pin_A = Noneself.pin_B = Nonedef getPinA(self):return int(input("给定A引脚的输入" + self.getlabel() + "-->"))def getPinB(self):return int(input("给定B引脚的输入" + self.getlabel() + "-->"))#单引脚门class UnaryGate(LogicGate):def __init__(self, n):super().__init__(n)self.pin = Nonedef getPin(self):return int(input("给定引脚的输入" + self.getlabel() + "-->"))#与门class AndGate(BinaryGate):def __init__(self, n):super().__init__(n)def performanceGateLogic(self):a = self.getPinA()b = self.getPinB()if a == 1 and b == 1:return 1else:return 0#与非门class NandGate(AndGate):def __init__(self, n):super().__init__(n)def performanceGateLogic(self):a = self.getPinA()b = self.getPinB()if a == 1 and b == 1:return 0else:return 1#异或门class XorGate(BinaryGate):def __init__(self, n):super().__init__(n)def performanceGateLogic(self):a = self.getPinA()b = self.getPinB()if a != b:return 1else:return 0def gatetest():g1 = XorGate("G1")print(g1.getoutput())

#1.15 数独游戏

#约定'.'为未填充的数据

board = [["5","3",".",".","7",".",".",".","."],["6",".",".","1","9","5",".",".","."],[".","9","8",".",".",".",".","6","."],["8",".",".",".","6",".",".",".","3"],["4",".",".","8",".","3",".",".","1"],["7",".",".",".","2",".",".",".","6"],[".","6",".",".",".",".","2","8","."],[".",".",".","4","1","9",".",".","5"],[".",".",".",".","8",".",".","7","9"]]class SudokuSolution:def solveSudoku(self, board) -> None: line =[[False] * 9 for _ in range(9)]column = [[False] * 9 for _ in range(9)]block = [[[False] * 9 for _a in range(3)] for _b in range(3)]valid = Falsespace = list()for i in range(9):for j in range(9):if board[i][j] == ".":space.append((i, j))else:digit = int(board[i][j]) - 1line[i][digit] = column[j][digit] =block[i//3][j//3][digit] = Truedef dfs(pos):nonlocal validif pos == len(space):valid = Truereturn i, j = space[pos]for digit in range(9):if line[i][digit] == column[j][digit] == block[i//3][j//3][digit] == False:line[i][digit] = column[j][digit] = block[i//3][j//3][digit] = Trueboard[i][j] = str(digit + 1) dfs(pos + 1)line[i][digit] = column[j][digit] = block[i//3][j//3][digit] = Falseif valid:return dfs(0)def Sudokutest():s1 = SudokuSolution()s1.solveSudoku(board)print(board)

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。