数据结构与算法分析_python_C1

Chapter 1
1-1 通过牛顿迭代法求解平方根

def squareroot(n):
    root = n/2 #initial guess will be 1/2 of n
    for k in range(20):
        root = (1/2) * (root + (n / root))
        
    return root
squareroot(9)
squareroot(4563)

1-2 Fraction类及其构造方法

class Fraction:
    def __init__(self,top,bottom):
        
        self.num = top
        self.den = bottom
        
myfraction = Fraction(3,5)
print(myfraction)

1-3 show方法

class Fraction:
    def __init__(self,top,bottom):
        
        self.num = top
        self.den = bottom
    def show(self):
        print(self.num, '/', self.den)
        
myf = Fraction(3,5)
myf.show()

1-4 str方法

class Fraction:
    def __init__(self,top,bottom):
        
        self.num = top
        self.den = bottom
    def __str__(self):
        return str(self.num) + "/" + str(self.den)

myf1 = Fraction(3,5)
print(myf1)
myf.__str__()

1-5 add方法

class Fraction:
    def __init__(self,top,bottom):
        
        self.num = top
        self.den = bottom
        
         
    def __str__(self):
        return str(self.num) + "/" + str(self.den)
    
    def __add__(self,otherfraction):
        newnum = self.num * otherfraction.den + self.den * otherfraction.num
        newden = self.den * otherfraction.den
        
        return Fraction(newnum, newden)

F1 = Fraction(1,4)
F2 = Fraction(1,2)
F3 = F1 + F2
print(F3)

1-6 gcd函数

def gcd(m,n):
    while m%n != 0:
        oldm = m
        oldn = n
        
        m = oldn
        n = oldm%oldn
        
    return n

1-7 改良版add方法

class Fraction:
    def __init__(self,top,bottom):
        
        self.num = top
        self.den = bottom
        
         
    def __str__(self):
        return str(self.num) + "/" + str(self.den)
    
    
    def __add__(self,otherfraction):
        newnum = self.num * otherfraction.den + self.den * otherfraction.num
        newden = self.den * otherfraction.den
        common = gcd(newnum, newden)
        
        return Fraction(newnum / common, newden / common)    

F1 = Fraction(1,4)
F2 = Fraction(1,2)
F3 = F1 + F2
print(F3)

1-8 eq方法

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

1-9 Fraction 类的完整实现

class Fraction:
    
    def __init__(self,top,bottom):
        
        self.num = top
        self.den = bottom
        
    def __str__(self):
        return str(self.num) + "/" + str(self.den)
    
    def show(self):
        print(self.num, '/', self.den)
        
    def __add__(self,otherfraction):
        newnum = self.num * otherfraction.den + self.den * otherfraction.num
        newden = self.den * otherfraction.den
        common = gcd(newnum, newden)
        
        return Fraction(newnum / common, newden / common)

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

1-10 超类LogicGate

class LogicGate:
    
    def __init__(self,n):
        self.label = n
        self.output = None
        
    def getLabel(self):
        return self.label
    
    def getOutput(self):
        self.output = self.performGateLogic()
        return self.output

1-11 BinaryGate类

class BinaryGate(LogicGate):
    
    def __init__(self,n):
        super().__init__(n)
        
        self.pinA = None
        self.pinB = None
        
    // # def getpinA(self):
	//#  return int(input("Enter Pin A input for gate" + self.getLabel() + "-->"))
    
    def getpinA(self):
        if self.pinA == None:
            return int(input("Enter Pin A input for gate" + self.getLabel() + "-->"))
        else:
            return self.pinA.getFrom().getOutput()
    
    def getpinB(self):
        return int(input("Enter Pin B input for gate" + self.getLabel() + "-->"))

1-12 UnaryGate类

class UnaryGate(LogicGate):
    
    def __init__(self,n):
        super().__init__(n)
        
        self.pin = None
        
    def getPin(self):
        return int(input("Enter Pin input for gate" + self.getLabel() + "-->"))

1-13.1 AndGate 类

class AndGate(BinaryGate):
    
    def __init__(self,n):
        super().__init__(n)
        
    def performGateLogic(self):
        a = self.getpinA()
        b = self.getpinB()
        if a == 1 and b == 1:
            return 1
        else:
            return 0

g1 = AndGate("G1")
g1.getOutput()

1-13.2 OrGate类

class OrGate(BinaryGate):
    
    def __init__(self,n):
        super().__init__(n)
        
    def performGateLogic(self):
        a = self.getpinA()
        b = self.getpinB()
        if a == 0 and b == 0:
            return 0
        else:
            return 1

g2 = OrGate("G2")
g2.getOutput()

1-13.3 NotGate类

class NotGate(BinaryGate):
    
    def __init__(self,n):
        super().__init__(n)
        
    def performGateLogic(self):
        a = self.getpinA()
//#         b = self.getpinB()
        if a == 0:
            return 1
        else:
            return 0

g3 = NotGate("G3")
g3.getOutput()

1-14 Connector类

class Connector:
    
    def __init__(self,fgate,tgate):
        self.fromgate = fgate
        self.togate = tgate
        
        tgate.setNextPin(self)
        
    def getFrom(self):
        return self.fromgate
    
    def getTo(self):
        return self.togate

1-15 setNextPin方法

  def setNextPin(self,source):
        if self.pinA == None:
            self.pinA = source
        else:
            if self.pinB == None:
                self.pinB = source
            else:
                raise RuntimeError("Error: NO EMPTY PINS")

1-16 修改后的getpinA方法

def getpinA(self):
    if self.pinA == None:
        return int(input("Enter Pin A input for gate" + self.getLabel() + "-->"))
    else:
        return self.pinA.getFrom().getOutput()

综合构造电路

class LogicGate:
    
    def __init__(self,n):
        self.label = n
        self.output = None
        
    def getLabel(self):
        return self.label
    
    def getOutput(self):
        self.output = self.performGateLogic()
        return self.output
    
    
class BinaryGate(LogicGate):
    
    def __init__(self,n):
        super().__init__(n)
        
        self.pinA = None
        self.pinB = None
        
//#     def getpinA(self):
//#         return int(input("Enter Pin A input for gate" + self.getLabel() + "-->"))
    
    def getpinA(self):
        if self.pinA == None:
            return int(input("Enter Pin A input for gate" + self.getLabel() + "-->"))
        else:
            return self.pinA.getFrom().getOutput()
    
    def getpinB(self):
        if self.pinB == None:
            return int(input("Enter Pin B input for gate" + self.getLabel() + "-->"))
        else:
            return self.pinB.getFrom().getOutput()
       
    
class UnaryGate(LogicGate):
    
    def __init__(self,n):
        super().__init__(n)
        
        self.pin = None
        
    def getPin(self):
        return int(input("Enter Pin input for gate" + self.getLabel() + "-->"))
    
class AndGate(BinaryGate):
    
    def __init__(self,n):
        super().__init__(n)
        
    def performGateLogic(self):
        a = self.getpinA()
        b = self.getpinB()
        if a == 1 and b == 1:
            return 1
        else:
            return 0
        

class OrGate(BinaryGate):
    
    def __init__(self,n):
        super().__init__(n)
    
    def setNextPin(self,source):
        if self.pinA == None:
            self.pinA = source
        else:
            if self.pinB == None:
                self.pinB = source
            else:
                raise RuntimeError("Error: NO EMPTY PINS")
                
    def performGateLogic(self):
        a = self.getpinA()
        b = self.getpinB()
        if a == 0 and b == 0:
            return 0
        else:
            return 1
        
        
class NotGate(BinaryGate):
    
    def __init__(self,n):
        super().__init__(n)
     
    def setNextPin(self,source):
        if self.pinA == None:
            self.pinA = source
        else:
            if self.pinB == None:
                self.pinB = source
            else:
                raise RuntimeError("Error: NO EMPTY PINS")
    
    def performGateLogic(self):
        a = self.getpinA()
//#         b = self.getpinB()
        if a == 0:
            return 1
        else:
            return 0
    

class Connector:
    
    def __init__(self,fgate,tgate):
        self.fromgate = fgate
        self.togate = tgate
        
        tgate.setNextPin(self)
        
    def getFrom(self):
        return self.fromgate
    
    def getTo(self):
        return self.togate
    
    def setNextPin(self,source):
        if self.pinA == None:
            self.pinA = source
        else:
            if self.pinB == None:
                self.pinB = source
            else:
                raise RuntimeError("Error: NO EMPTY PINS")
g1 = AndGate("G1")
g2 = AndGate("G2")
g3 = OrGate("G3")
g4 = NotGate("G4")
c1 = Connector(g1,g3)
c2 = Connector(g2,g3)
c3 = Connector(g3,g4)
g4.getOutput()

实现简单方法的getNum和getDen,他们分别返回分数的分子和分母

class Fraction:
    def __init__(self,top,bottom):
        
        self.num = top
        self.den = bottom
        
    def __getnum__(self):
        print(self.num)
    def __getden__(self):
        print(self.den)
myf=Fraction(2,5)
myf.__getnum__()
myf.__getden__()     

如果所有分数从一开始就是最简形式会更好。修改Fraction类的构造方法,立即使用最大公因数来简化分数。注意,这意味着add不再需要简化结果.

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):
        
        self.num = top
        self.den = bottom
        
         
    def __str__(self):
        return str(self.num) + "/" + str(self.den)
    
    
    def __add__(self,otherfraction):
        newnum = self.num * otherfraction.den + self.den * otherfraction.num
        newden = self.den * otherfraction.den
        common = gcd(newnum, newden)
        
        return Fraction(newnum/common, newden/common)
F1 = Fraction(1,4)
F2 = Fraction(1,2)
F3 = F1 + F2
print(F3)

实现下列简单的算术运算:sub,mul,truediv

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):
        
        self.num = top
        self.den = bottom
        
         
    def __str__(self):
        return str(self.num) + "/" + str(self.den)
    
    
    def __add__(self,otherfraction):
        newnum = self.num * otherfraction.den + self.den * otherfraction.num
        newden = self.den * otherfraction.den
        common = gcd(newnum, newden)
        return Fraction(newnum/common, newden/common)
        
    def __sub__(self,otherfraction):
        newnum = self.num * otherfraction.den - self.den * otherfraction.num
        newden = self.den * otherfraction.den
        common = gcd(newnum, newden)
        return Fraction(newnum/common, newden/common)
    
    def __mul__(self,otherfraction):
        newnum = self.num * otherfraction.num
        newden = self.den * otherfraction.den
        common = gcd(newnum, newden)
        return Fraction(newnum/common, newden/common)
    
    def __truediv__(self,otherfraction):
        newnum = self.num * otherfraction.den
        newden = self.den * otherfraction.num
        common = gcd(newnum, newden)
        return Fraction(newnum/common, newden/common)
F1 = Fraction(1,4)
F2 = Fraction(1,2)
F3 = F1 + F2
F4 = F1 - F2
F5 = F1 * F2
F6 = F1 / F2
print("F3 = ",F3)
print("F4 = ",F4)
print("F5 = ",F5)
print("F6 = ",F6)

实现下列关系运算 gt,ge,lt,le和ne

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):
        
        self.num = top
        self.den = bottom
        
         
    def __str__(self):
        return str(self.num) + "/" + str(self.den)
    
    
    def __add__(self,otherfraction):
        newnum = self.num * otherfraction.den + self.den * otherfraction.num
        newden = self.den * otherfraction.den
        common = gcd(newnum, newden)
        return Fraction(newnum//common, newden//common)
        
    def __sub__(self,otherfraction):
        newnum = self.num * otherfraction.den - self.den * otherfraction.num
        newden = self.den * otherfraction.den
        common = gcd(newnum, newden)
        return Fraction(newnum//common, newden//common)
    
    def __mul__(self,otherfraction):
        newnum = self.num * otherfraction.num
        newden = self.den * otherfraction.den
        common = gcd(newnum, newden)
        return Fraction(newnum//common, newden//common)
    
    def __truediv__(self,otherfraction):
        newnum = self.num * otherfraction.den
        newden = self.den * otherfraction.num
        common = gcd(newnum, newden)
        return Fraction(newnum//common, newden//common)
    
    def __gt__(self,otherfraction):
        if self.num * otherfraction.den > self.den * otherfraction.num:
            print('%s is greater' %self.__str__())
        else:
            print('%s is not greater' %self.__str__())
        
    def __ge__(self,otherfraction):
        if self.num * otherfraction.den >= self.den * otherfraction.num:
            print('%s is greater' %self.__str__())
        else:
            print('%s is not greater' %self.__str__())
    
    def __lt__(self,otherfraction):
        if self.num * otherfraction.den < self.den * otherfraction.num:
            print('%s is greater' %self.__str__())
        else:
            print('%s is not greater' %self.__str__())
            
    def __le__(self,otherfraction):
        if self.num * otherfraction.den <= self.den * otherfraction.num:
            print('%s is greater' %self.__str__())
        else:
            print('%s is not greater' %self.__str__())
            
    def __ne__(self,otherfraction):
        
        if self.num * otherfraction.den == self.den * otherfraction.num:
            print('%s is greater' %self.__str__())
        else:
            print('%s is not greater' %self.__str__())
if __name__=="__main__": 
    F11 = Fraction(6,7)
    F12 = Fraction(1,21)
    
    f11 = F11.__gt__(F12)
    f12 = F11.__ge__(F12)
    f13 = F11.__lt__(F12)
    f14 = F11.__le__(F12)
    f15 = F11.__ne__(F12)
                
    print(f11)
    print(f12)
    print(f13)
    print(f14)
    print(f15)

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

class Fractionn:
    def __init__(self,top,bottom):
        if isinstance(top,int) and isinstance(bottom,int):
            self.num = top
            self.den = bottom
        else:
            print("error")
f1 = Fractionn(1.1,10)
print(f1)  

假设负的分数是由负的分子和正的分母构成。使用负的分母会导致某些关系运算符返回错误的结果。一般来说,这是多余的限制。请修改构造方法,使用户能够出啊内负的分母,并且所有的运算符都能返回正确的结果。

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):
        n = gcd(top,bottom)
        self.num = top//n
        self.den = bottom//n
        
    def __str__(self):
        return str(self.num) + '/' + str(self.den)
    
    def show(self):
        print(self.num, '/', self.den)
        
    def __gt__(self,otherfraction):
        if [x>0 for x in [self.num,otherfraction.num]] or [x<0 for x in [self.num,otherfraction.num]]:
            if self.den * otherfraction.num > self.num * otherfraction.den:
                print('%s is greater' % self.__str__())
            else:
                print('%s is not greater' % self.__str__())  
        else:
            if self.den * otherfraction.num < self.num * otherfraction.den:
                print('%s is greater' % self.__str__())
            else:
                print('%s is not greater' % self.__str__())
                
    
    def __ge__(self,otherfraction):
        if self.num * otherfraction.den >= self.den * otherfraction.num:
            print('%s is greater' %self.__str__())
        else:
            print('%s is not greater' %self.__str__())
    
    def __lt__(self,otherfraction):
        if self.num * otherfraction.den < self.den * otherfraction.num:
            print('%s is greater' %self.__str__())
        else:
            print('%s is not greater' %self.__str__())
            
    def __le__(self,otherfraction):
        if self.num * otherfraction.den <= self.den * otherfraction.num:
            print('%s is greater' %self.__str__())
        else:
            print('%s is not greater' %self.__str__())
            
    def __ne__(self,otherfraction):
        
        if self.num * otherfraction.den == self.den * otherfraction.num:
            print('%s is greater' %self.__str__())
        else:
            print('%s is not greater' %self.__str__())
if __name__=="__main__": 
    F61 = Fraction(3,-7)
    F62 = Fraction(1,21)
    
    f61 = F62.__gt__(F61)
    f62 = F61.__ge__(F62)
    f63 = F61.__lt__(F62)
    f64 = F61.__le__(F62)
    f65 = F61.__ne__(F62)
                
    print(f61)
    print(f62)
    print(f63)
    print(f64)
    print(f65)
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值