如何在Python中返回范围内的最大数量

时间:2013-04-24 09:45:05

标签: python

这是我在python中的公式

实现数学函数f(x)= -5 x5 + 69 x2 - 47

定义数学函数

def math_formula(x):

# This is the formula
    math_formula = -5 * (x**5) + 69 *(x**2) - 47
    return math_formula

打印我们范围内的值

for value in range (0,4):
    print 'For f(',(value),')', 'the number is:' , math_formula(value)

print ''    
print ('The the maximum of these four numbers is:'), max(math_formula(value))

该函数返回f(0)到f(3)的所有数字。

有人可以回答以下问题: 为什么此打印件不会返回最大数量?

print ('The the maximum of these four numbers is:'), max(math_formula(value))

它返回范围中较高的负数。 我不知道如何返回最大正数。如何返回最大正数。

4 个答案:

答案 0 :(得分:3)

max(math_formula(value) for value in range(0, 4))

答案 1 :(得分:1)

max()需要处理序列。您需要将所有计算的列表传递给它。试试这个变化:

results = []
for value in range(0, 4):
    print 'For f(',(value),')', 'the number is:' , math_formula(value)
    results.append(math_formula(value)) # add the value to the list

print ''
print 'The maximum of these four numbers is:', max(results)

您还可以简化math_formula方法:

def math_formula(x):
    return -5 * (x**5) + 69 *(x**2) - 47

答案 2 :(得分:0)

尝试:

max((math_formula(value) for value in xrange(0,4)))

修改

对于你的口译员:

max([math_formula(value) for value in range(0,4)])

答案 3 :(得分:0)

我们也可以使用此max(a[i:i+k]) 获得范围内的最大值