PTA-浙大版《Python 程序设计》AC解答汇总-第二章

# 第2章-1 计算 11+12+13+...+m (30分)
def demo_2_1():
    print ("sum =",sum(list(range(11,int(input())+1))))


# 第2章-2 计算分段函数[1] (10分)
def demo_2_2():
    x=float(input())
    res=0
    if x!=0:res= 1./x
    print("f(%.1f) = %.1f"%(x,res))


# 第2章-3 阶梯电价 (15分)
def demo_2_3():
    x=float(input())
    res=0
    if x<0:
        print("Invalid Value!")
    elif x<=50:
        res = x*0.53
        print("cost = %.2f"%res)
    else:
        res = 50*0.53+(x-50)*0.58
        print("cost = %.2f"%res)


# 第2章-4 特殊a串数列求和 (20分)
def demo_2_4():
    a,n=input().split()
    print("s = %d"%sum([int(a*i) for i in range(1,int(n)+1)]))


# 第2章-5 求奇数分之一序列前N项和 (15分)
def demo_2_5():
    print("sum = %.6f"%sum([ 1./(2*x-1) for x in range(1,int(input())+1)]))


# 第2章-6 求交错序列前N项和 (15分)
def demo_2_6():
    print("%.3f"%sum([i/(2*i-1) if i%2==1 else -i/(2*i-1) for i in range(1,int(input())+1)]))


# 第2章-7 产生每位数字相同的n位数 (30分)
def demo_2_7():
    a,b=input().split(",")
    print(a.strip()*int(b))


# 第2章-8 转换函数使用 (30分)
def demo_2_8():
    a,b=input().split(",")
    print(int(a,int(b)))


# 第2章-9 比较大小 (10分)
def demo_2_9():
    print(*sorted(map(int,input().split())),sep="->")


# 第2章-10 输出华氏-摄氏温度转换表 (15分)
def demo_2_10():
    lower,upper=map(int,input().split())
    if lower>upper or upper>100:
        print("Invalid.")
    else:
        print("fahr celsius")
        for i in range(lower,upper+1,2):
            print("{:d}{:>6.1f}".format(i,5*(i-32)/9))


# 第2章-11 求平方与倒数序列的部分和 (15分)
def demo_2_11():
    m,n=map(int,input().split())
    print("sum = %.6f"%sum([float(x*x+1./x) for x in range(m,n+1)]))


# 第2章-12 输出三角形面积和周长 (15分)
def demo_2_12():
    import numpy as np
    a,b,c=map(int,input().split())
    s=(a+b+c)/2
    a2=s*(s-a)*(s-b)*(s-c)
    if a2>0:
        print("area = %.2f; perimeter = %.2f"%(np.sqrt(a2),(a+b+c)))
    else:
        print("These sides do not correspond to a valid triangle")


# 第2章-13 分段计算居民水费 (10分)
def demo_2_13():
    x=int(input())
    y=0
    if x<=15:
        y=4.*x/3
    else:
        y=2.5*x-17.5
    print("%.2f"%y)
        

# 第2章-14 求整数段和 (15分)
def demo_2_14():
    a,b=map(int,input().split())
    cnt,res=0,0
    for i in range(a,b+1):
        print("{:>5}".format(i),end="")
        res=res+i
        cnt=cnt+1
        if cnt%5==0 and i!=b:print("\n",end="")
    print("\nSum = %d"%res)

猜你喜欢

转载自blog.csdn.net/qq_34451909/article/details/107928538