4 回答

TA貢獻1796條經驗 獲得超4個贊
您可以選擇將其放入函數中嗎?如果是這樣,盡早退出是你的朋友:
def is_winner(nums, middle):
# The last number must be a zero
if nums[-1] != 0:
return False
# All of the starting numbers must be less than 7
if not all(num < 7 for num in nums[:middle]):
return False
# All of the ending numbers must be at least 7
if not all(num >= 7 for num in nums[middle:-1]):
return False
# If all of those are OK, then we've succeeded
return True
# This will print False because it doesn't end in 0.
position = [3, 6, 4, 2, 5, 0, 10, 12, 7, 8]
print(is_winner(position, 6))
# This will print True because it meets the requirements.
position = [3, 6, 4, 2, 5, 0, 10, 12, 7, 8, 0]
print(is_winner(position, 6))
# This will print False because a number in the first part is greater than 7
position = [3, 6, 4, 2, 5, 0, 10, 12, 7, 8, 0]
print(is_winner(position, 7))
# This will print False because a number in the second part is not at least 7
position = [3, 6, 4, 2, 5, 0, 10, 12, 7, 8, 0]
print(is_winner(position, 5))
看看這個函數如何變得非常簡單和可讀?在每一步中,如果不滿足要求,您就會停止。您不必跟蹤狀態或任何東西;你只需返回 False 即可。如果您到達函數末尾并且沒有失敗任何測試,那么 ta-da!您成功了并且可以返回 True。
順便說一句,根據你的例子,第二個要求應該是x >= 7,而不是x > 7。如果不正確,請更新代碼和示例以匹配。

TA貢獻1752條經驗 獲得超4個贊
您的代碼中可能有兩個錯誤:
第一個if語句中的行必須是?if position[i]<7 and position[-1]!=0:
,但您已經編寫了... and position[i]!=0
其次,您的第二個 for 循環不會被執行,因為它的iterator 是range(6-where,-1)
, range 函數默認給出一個升序迭代器,所以在你的情況下迭代器是空的。對于降序列表,請向range func 添加一個step參數并使用。?這里最后一個-1是范圍函數的步長range(6-where, -1, -1)

TA貢獻1895條經驗 獲得超7個贊
你的代碼看起來有點糾結。首先,使用布爾值和適當的名稱a。例如listValid = True。但沒有它也是可能的。
position=[3,6,4,2,5,0,10,12,7,8]
splitIndex = 6 - 1
if all([value < 7 for value in position[:splitIndex]]):
if all([value > 6 for value in position[splitIndex:-1]]):
if position[-1] == 0:
print("Yeah")

TA貢獻1831條經驗 獲得超4個贊
在第一個 if 語句中,您有位置 [i] 而不是位置 [-1]。
這里還有一些改進的、更簡單的代碼:
position=[3,6,4,2,5,0,10,12,7,8]
x = 5
valid_list = True
for i in range(x):
if position[i] >= 7 or position[i] == 0:
valid_list = False
for i in range(len(position) - x - 1):
if position[x + i] < 7 or position[i] == 0:
valid_list = False
if valid_list and position[-1] == 0:
print('Yeah')
添加回答
舉報