[英]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.