0
点赞
收藏
分享

微信扫一扫

蓝桥杯 第1天 Python基础

去年寒假参加过蓝桥杯的python组,不过因为没经验只拿了省二。

今年已经把算法笔记给过了两遍,比起去年要好不少,但是因为学算法笔记一直用c,从今天开始正式回归python。

很快地把python语法过了一下,类与继承之前没注意过,而且去年刷题也没用上。

1.类

​
def gcd(m,n):
    if(n==0):
        return m
    else:
        return gcd(n,m%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 __eq__(self, other):
        firstnum=self.num*other.den
        secondnum=other.num*self.den
        return firstnum==secondnum
f1=fraction(1,4)
f2=fraction(1,2)
f3=f1+f2
print(f3)

​

2.类的继承

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 pina "+self.getlabel()+"-->"))
    def getpinb(self):
        return int(input("Enter pinb "+self.getlabel()+"-->"))
class andgate(binarygate):
    def __eq__(self, other):
        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")
print(g1.getoutput())
举报

相关推荐

0 条评论