[英]Write a program to find the greatest number in a list using python?
我的解决办法是:
numbers = [1, 2, 3, 5, 9, 6, 101, 55, 7, 1, 3, 88, 99, 101, 6, 88, 66, 101, 6, 101, 55, 1001]
n = len(numbers)
for x in range(n):
y = 0
while y < n:
if numbers[x] >= numbers[y]:
y += 1
else:
break
else:
z = x
print(f'Greatest number = {numbers[z]}')
我知道这很复杂,但对吗? 还有一件事——即使我对每个我能做的数字列表都得到了正确的答案,但 pycharm 显示了一个警告——名称“z”可以是未定义的。 为什么会这样,我该如何删除它//
是的,使用两个循环只是为了找到最大值是复杂且无效的。 甚至可以使用 max 函数
numbers = [1, 2, 3, 5, 9, 6, 101, 55, 7, 1, 3, 88, 99, 101, 6, 88, 66, 6, 101, 55, 1001]
print(max(numbers))
对于编写自己的逻辑,这实际上更简单。
numbers = [1, 2, 3, 5, 9, 6, 101, 55, 7, 1, 3, 88, 99, 101, 6, 88, 66, 6, 101, 55, 1001]
maxi = numbers[0]
for i in numbers:
if i > maxi:
maxi = i
print("Greatest number: ", maxi)
else:
块仅在while
循环正常结束时才执行,而不是通过执行break
语句。
由于您只在else:
块中设置了z
,如果循环由于break
语句而结束,则不会设置z
。
可能是两个循环的数学逻辑确保了至少一个内部循环将在不执行break
情况下完成。 但是 PyCharm 无法判断这总是正确的,因此它会发出警告。
如果您确定循环不会在不设置z
情况下结束,您可以在 PyCharm 中取消警告。
max_number = max(numbers)
print('Greatest number = {}'.format(max_number))
对于pycharm警告,是因为在else块中定义并赋值的变量z,不像java python是动态类型的,不需要变量声明
做 z = x 没有意义。 做就是了:
numbers = [1, 2, 3, 5, 9, 6, 101, 55, 7, 1, 3, 88, 99, 101, 6, 88, 66, 101, 6, 101, 55, 1001]
n = len(numbers)
for x in range(n):
y = 0
while y < n:
if numbers[x] >= numbers[y]:
y += 1
else:
break
print(f'Greatest number = {numbers[z]}')
看起来你正在使用 C/C++ 方法来解决它,python 有很多内置函数可以让你的生活更轻松。 在这种情况下,您可以使用max()函数。
最短的路
numbers = [1, 2, 3, 5, 9, 6, 101, 55, 7, 1, 3, 88, 99, 101, 6, 88, 66, 101, 6, 101, 55, 1001]
print(f'Greatest number = {max(numbers)}')
Greatest number = 1001
您收到此通知是因为z变量仅在else块中声明。 如果您的代码将从while块中退出(不是在这种情况下,但无论如何)并且永远不会进入else ,您将收到一个错误:
UnboundLocalError: local variable 'z' referenced before assignment
简单的例子:
def test(x):
...: if x == 1:
...: z = x
...: else:
...: pass
...: print(z)
...:
test(1)
1
test(2)
Traceback (most recent call last):
File "/home/terin/regru/venvs/.dl/lib/python3.8/site-packages/IPython/core/interactiveshell.py", line 3331, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-13-14ddcd275974>", line 1, in <module>
test(2)
File "<ipython-input-11-43eaa101b10d>", line 6, in test
print(z)
UnboundLocalError: local variable 'z' referenced before assignment
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.