In: Computer Science
Smaller index
Complete the following function according to its docstring using a while loop. The lists we test will not all be shown; instead, some will be described in English. If you fail any test cases, you will need to read the description and make your own test.
def smaller_index(items):
""" (list of 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
"""
def smaller_index(items):
""" (list of 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
"""
# iterate over items
for i in range(len(items)):
# found
if items[i] < i:
return i
# not found
return -1
# testing
print(smaller_index([2, 5, 7, 99, 6]))
print(smaller_index([-5, 8, 9, 16]))
print(smaller_index([5, 8, 9, 0, 1, 3]))
.
Screenshot:
Output:
.