![](/img/trans.png)
[英]Counting the pairs in a list such that their first index is less than the second but the first element is greater than the second
[英]Returning the index of the first integer in a list that is less than its index
我是 python 的初學者,我不知道如何做到這一點。
有人知道我如何修復我的代碼嗎?
def smaller_index(items: list[int]) -> int:
"""
Return the index of the first integer in items that is less than its index,
or -1 if no such integer exists in items.
>>> smaller_index([2, 5, 7, 99, 6])
-1
>>> smaller_index([-5, 8, 9, 16])
0
>>> smaller_index([5, 8, 9, 0, 1, 3])
3
"""
min_value = min(items)
if items.count(min_value) > 1:
return [i for i, x in enumerate(items) if x == min(items)]
else:
return items.index(min(items))
這是此問題的解決方案。
def smaller_index(items: list) -> int:
"""
Return the index of the first integer in items that is less than its index,
or -1 if no such integer exists in items.
#>>> smaller_index([2, 5, 7, 99, 6])
-1
#>>> smaller_index([-5, 8, 9, 16])
0
#>>> smaller_index([5, 8, 9, 0, 1, 3])
3
"""
for i in range(len(items)):
if items[i] < i:
return i
return -1
print(smaller_index([5, 8, 9, 0, 1, 3]))
邏輯分解:
def smaller_index(items: list) -> int:
for i, n in enumerate(items):
if n < i:
return i
return -1
假設我理解你想要做什么,這可以像你想要的那樣簡單。
快樂編碼!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.