Discuss / Python / 作业,一个不用迭代的方法

作业,一个不用迭代的方法

Topic source

竹叶lcc

#1 Created at ... [Delete] [Delete and Lock User]

def finddx(L):

    x,y=0,1

    M=L[:]#复制一个list M 

    N=L[:]#复制一个list N 

    if len(L)!=0:#考虑到list为空值的情况

        while y<len(M):

            if M[x]<=M[y]:

                M.pop(y)

            else:

                M.pop(x)#两个相邻的数比较,大的删去

            if N[x]>=N[y]:

                N.pop(y)

            else:

                N.pop(x)#两个相邻的数比较,小的删去

        return M[0],N[0]

    else:

        return (None,None)#list为空,则输出None

di=[45,67,89,12,41,345,9,5673,8,23,8,1,3,56]

finddx(di)

输出结果是:(1, 5673)

唯一想不通是‘5673’前有个空格……

竹叶lcc

#2 Created at ... [Delete] [Delete and Lock User]

def findmaxmin(L):

    if len(L)==0:

        return None,None

    else:

        max=min=L[0]

        for i in L:

            if max<i:

                max=i

            if min>i:

                min=i   

    return min,max

di=[45,45,67,89,12,41,345,9,5673,8,23,8,1,3,56]

findmaxmin(di)

竹叶lcc

#3 Created at ... [Delete] [Delete and Lock User]

def findmaxmin(L):

    from collections import Iterable

    if isinstance(L, Iterable) is True:

        if len(L)==0:

            return None,None

        else:

            max=min=L[0]

            for i in L:

                if max<i:

                    max=i

                if min>i:

                    min=i   

        return min,max

    else:

        return '不可迭代'

di=[45,67,89,12,41,345,9,5673,8,23,8,1,3,56]

li=123445678

print(findmaxmin(di),findmaxmin(li))

输出结果为:(1, 5673) 不可迭代


  • 1

Reply