Discuss / Python / 我又有疑惑了,求大佬指点

我又有疑惑了,求大佬指点

Topic source

佳jiajia乐

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

def find_min_max(L):

    if L==[]:

        return None,None

    else:

        min=L[0]

        max=L[0]

        for i in L:

            if i>L[0]:

                max=i

            if i<L[0]:

                min=i              

    return (max,min)

l=[2,6,9,56,65,36,31,1,5,7]

s=find_min_max(l)

print('s=',s)

为什么这个程序出来,最大值永远是最小值后面的最大值,他是输出(7,1),和大家的代码对比了一下,没太大出入

因为if判断的时候始终是L[0],没有对max和min进行更新。

佳jiajia乐

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

那要怎么修改哦

就你个

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

if i > L[]: 这个判断改成 if i >max:           if i < min:

talyerbooming

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

楼上几位都把我整蒙了,问题是:你把return (min,max)写成了return (max,min)。。。

talyerbooming

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

我傻了,重看了代码,问题确实是没有把L[0]替换成min和max

1.迭代进行比较的时候比较错了,不是i和L[0]比,是i和max或者min比;

2.最后return顺序反了(不影响大局)

def findMinAndMax(L):

    if not L:

        return (None,None)

    Min = L[0]

    Max = L[0]

    for x in L:

        if x > Max :

            Max = x

        if x < Min :

            Min = x

    return (Min,Max)


  • 1

Reply