Python - 在没有使用max()的情况下找到3个数中最大的2个

时间:2012-02-26 05:40:12

标签: python function variables

我正在寻找这里找到的同一问题的答案:

Python - Find the greatest number in a set of numbers

但是,我想构建自己的程序,而不是使用内置函数max()。这就是我现在所拥有的,但是由于范围可变,我认为这是一个错误。

def two_of_three(a, b, c):
    if a>=b:
        x=a
    else:
        x=b
    if b>=c:
        y=b 
    else:
        y=c
    if a>=c:
        x=a
    else:
        x=c
    return x**x+y**y

assert two_of_three(3,4,5)==41
assert two_of_three(0,1,2)==5
assert two_of_three(9,21,89)==8362

以下是我遇到的错误:

Traceback (most recent call last):
File "python_hw1.py", line 32, in <module>
assert two_of_three(3,4,5)==41
AssertionError

7 个答案:

答案 0 :(得分:2)

在Python中,**表示to the power of。您可能正在寻找return x**2 + y**2

答案 1 :(得分:1)

<强> Sol.1

def two_biggest(a, b, c):
    if a>=b>=c:
        print a, b, 'are the biggest two'
    elif b>=c>=a:
        print b, c, 'are the biggest two'
    else:
        print c, a, 'are the biggest two'

<强> Sol.2

def two_biggest(a, b, c):
    nums = set([a, b, c])
    smallest = min(nums) # not max (trollface :P)
    nums.remove(smallest)
    print "the two largest numbers are", ' and '.join(map(str, nums))

答案 2 :(得分:1)

您的代码中有一个错误,允许返回两次相同的值:

def two_of_three(a, b, c):
    if a>=b:
        x=a
    else:
        x=b
    if b>=c:
        y=b 
    else:
        y=c
    if a>=c:
        x=a
    else:
        x=c
    print x, y

>>> two_of_three(3,4,5)
#5 5

<强>更新

我没有对此进行测试,因为我正在通过手机进行更新,但是这样的事情呢?

vals = [3,4,5]
twoLargest = sorted(vals)[-2:]

让sort函数自然地将最大的函数放在最后并取最后两个?

def biggestTwo(*args):
    return sorted(args)[-2:]

答案 3 :(得分:0)

如果您需要的是最大数字(不是变量名称),您可以尝试使用列表推导:

In : (a,b,c)
Out: (7, 3, 8)

In : [x for x in (a,b,c) if (x > a) | (x > b) | ( x > c)]
Out: [7, 8]

当两个或多个数字相等时(例如7,7,9)

,你必须根据你想要的结果进行调整。

答案 4 :(得分:0)

如果问题是避免使用bultin max函数,请编写自己的函数:

def mymax(l):
    x=float("-inf")
    for i in l:
       if i>x: x=i
    return x 

如果您想要列表中n个最大值的列表,您也可以自己编写其中一个:

def nmax(pl,n=1):
    r,l=[],[]
    for e in pl:
        l.append(e)
    for x in range(0,n):
        max_found=float("-inf")
        for i, v in enumerate(l):
            if v>max_found: 
                max_found=v
                max_index=i

        r.append(max_found)
        del l[max_index]

    return r   

测试它:

>>> import random
>>> rl=random.sample(range(1000),10)     
>>> print rl
[183, 456, 688, 263, 452, 613, 789, 682, 589, 493]        
>>> print nmax(rl,2)
[789, 688]

或者,如果您被允许使用内置sorted,则可以在一行中执行此操作:

>>> sorted(rl)[-2:]
[789, 688]

答案 5 :(得分:0)

我的解决方案如下:

def two_of_three(a, b, c):
    """Return x**2 + y**2, where x and y are the two largest of a, b, c."""
    return sum( map( lambda x: x**2, ( (a, b) if (a>=b>=c) else ((b, c) if (b>= c>=a) else (a, c))) ) )

答案 6 :(得分:0)

l=[2,3,8,5,4]
l.sort()
l[-1]
8