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 = m
        oldn = n
        m = oldn
        n = oldm % oldn
    return n

class Fraction():

    def __init__(self, top, bottom):
        if type(top) != int or type(bottom) != int:
            raise RuntimeError('not int var inputed')
        self.num = top
        self.den = bottom
        common = gcd(self.num, self.den)
        self.num //= common
        self.den //= common
        print(self.num,self.den)

    def getNum(self):
        return self.num

    def getDen(self):
        return self.den

    def 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.den
        newnum = self.den * other.num + other.den * self.num
        return Fraction(newnum, newden)

    def __radd__(self, other):
        newden = self.den * other.den
        newnum = self.den * other.num + other.den * self.num
        return Fraction(newnum, newden)

    def __sub__(self, other):
        newden = self.den * other.den
        newnum = other.den * self.num - self.den * other.num
        return Fraction(newnum, newden)

    def __mul__(self, other):
        newden = self.den * other.den
        newnum = self.num * other.num
        return Fraction(newnum, newden)

    def __truediv__(self, other):
        newden = self.den * other.num
        newnum = self.num * other.den
        return Fraction(newnum, newden)

    def __eq__(self, other):
        return self.num * other.den == self.den * other.num

    def __gt__(self, other):
        return self.num * other.den > self.den * other.num

    def __ge__(self, other):
        return self.num * other.den >= self.den * other.num

    def __le__(self, other):
        return self.num * other.den <= self.den * other.num

    def __lt__(self, other):
        return self.num * other.den < self.den * other.num

    def __ne__(self, other):
        return self.num * other.den != self.den * other.num

def fractiontest():
    myfraction1 = Fraction(1, -1)
    myfraction2 = Fraction(1, -2)
    print(myfraction1 + myfraction2)

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

#门的基类

class LogicGate():

    def __init__(self, n):
        self.label = n
        self.output = None
    
    def getlabel(self):
        return self.label

    def getoutput(self):
        self.output = self.performanceGateLogic()
        return self.output
#双引脚门
class BinaryGate(LogicGate):
    
    def __init__(self, n):
        super().__init__(n)
        self.pin_A = None
        self.pin_B = None
    
    def 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 = None

    def 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 1
        else:
            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 0
        else:
            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 1
        else:
            return 0

def 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 = False
        space = 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]) - 1
                    line[i][digit] = column[j][digit] =block[i//3][j//3][digit] = True
        
        def dfs(pos):
            nonlocal valid
            if pos == len(space):
                valid = True
                return 
            
            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] = True
                    board[i][j] = str(digit + 1) 
                    dfs(pos + 1)
                    line[i][digit] = column[j][digit] = block[i//3][j//3][digit] = False
                if valid:
                    return 

        dfs(0)

def Sudokutest():
    s1 = SudokuSolution()
    s1.solveSudoku(board)
    print(board)

  • 4
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值