gpt4 book ai didi

python - 创建 100 个随机整数的列表,返回最大值

转载 作者:太空宇宙 更新时间:2023-11-04 07:33:52 24 4
gpt4 key购买 nike

编写一个 Python 函数,它将获取 0 到 1000 之间的 100 个随机整数的列表,并返回最大值。 (注意:有一个名为 max 的内置函数,但假装你不能使用它。)

这是我尝试过的:

import random

list = []
for i in range(100):
list.append(random.randint(0,1000))

def max(list):
#sort list from least to greatest
answer = list.sort()
#get last item in list (max value)
list.pop()

return max

print (max(list))

如您所见,我感到困惑的是如何正确使用 sort 和 pop 方法在 max 函数中返回最大值。我目前得到:

ParseError: bad input on line 12

这是哪一行:

list.pop()

不确定如何更正此问题。谢谢。

最佳答案

1) 你的缩进是关闭的

2) 你成功地用 4 行代码覆盖了 2 个 Python 内置函数(max()list()))

3) my_list.sort() 不返回列表。它就地操作,就地对列表进行排序。相反,sorted(my_list) 确实会返回一个列表,因此您可以执行 my_list.sort()my_list = sorted(my_list) .

4) 你的 return 是错误的。

请看下面的代码:

a_list = []
for i in range(100):
a_list.append(random.randint(0, 1000))

def my_max(my_list):
return sorted(my_list)[-1] # here, the list we passed gets sorted and its last item is retrieved (item with index -1)

print(my_max(a_list))

其他有点自大的有趣答案(向@Rob 致敬):

def my_max(my_list):
return min(l, key:lambda i: 1/i)

def my_max(my_list):
return min(l, key:lambda i: -i)

关于python - 创建 100 个随机整数的列表,返回最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40916866/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com