PAT-B 1012. 数字分类(python)

1. py中初始数组,a1=a2=a3=a4=a5=[],  这样a1,a2,a3,a4,a5是指向同一个链表的引用。这和C不一样的。

2. round(number, significant)可以用来四舍五入小数

3. 暂未发现built-in中有average函数,用的是float(sum(a4)) / len(a4)


源码:

if __name__ == "__main__" :
    # initialize them seperately
    a1=[]
    a2=[]
    a3=[]
    a4=[]
    a5=[]
    
    num = raw_input().split(' ')
    for i in range(int(num[0])) :
        now = int(num[i+1])
        if now%10==0 :
            a1.append(now)
        elif now%5==1 :
            a2.append(now)
        elif now%5==2 :
            a3.append(now)
        elif now%5==3 :
            a4.append(now)
        elif now%5==4 :           # cannot use "else" straight, use this contrain
            a5.append(now)

    if a1==[] :
        print "N",
    else :
        print sum(a1),

    if a2==[] :
        print "N",
    else :
        a2_ans=0
        for i in range(len(a2)) :
            if i%2==0 :
                a2_ans = a2_ans + a2[i]
            else :
                a2_ans = a2_ans - a2[i]
        print a2_ans,

    if a3==[] :
        print "N",
    else :
        print len(a3),

    if a4==[] :
        print "N",
    else :
        print round(float(sum(a4))/len(a4), 1),

    if a5==[] :
        print "N"
    else :
        print max(a5)


你可能感兴趣的:(python,PAT-B)