如何从列表的最后一个到第一个搜索数字的索引



我正在检查文档,以找到从最后到第一的数字索引。我可以使用-list.index(数字,开始,结束(。在我的例子中,如果我省略了开始和结束,我不会得到任何异常。然而,当我将开始更改为最后一个索引,并将结束更改为第一个元素索引(即0(时,会出现异常。我确信我做错了什么,但我无法思考这里出了什么问题。

def nonConstructibleChange(coins):
# o(log n) - sorting
coins.sort() # O(log n)
max_amount = sum(coins)
print(max_amount)
# range is [start, end)
if len(coins) == 0:
return 1
for change in range(1, max_amount+1):
if change == 1:
if 1 not in coins:
return 1 
else:
max_limit = change - 1        
while max_limit not in coins and max_limit != -1:
max_limit -=1
print(coins.index(max_limit, len(coins)-1, 0))  # throws exception
print(coins.index(max_limit)) # this works



if __name__ == '__main__':
coins = [5, 7, 1, 1, 2, 3, 22]
nonConstructibleChange(coins)

您可以通过在反向列表上应用索引函数来查找元素最后一次出现的索引。在您的情况下,这将是:

print(coins[::-1].index(max_limit))
def nonConstructibleChange(coins):
# o(log n) - sorting
coins.sort() # O(log n)
max_amount = sum(coins)
num = None
#print(coins)
#print(max_amount)
# range is [start, end)
if len(coins) == 0:
return 1
for change in range(1, max_amount+1):
if change == 1:
if 1 not in coins:
return 1 
else:
max_limit = change        
while max_limit not in coins and max_limit != -1:
max_limit -=1
right_index = coins.index(max_limit)
while 1:
try:

# the last index is not included therefore len(coins)
right_index = coins.index(max_limit, right_index +1 , len(coins))
except ValueError:
# print(f'final right_index = {right_index}')
break 

print(f'right_index = {right_index}')
print(f'change = {change}')
print(f'max_limit = {max_limit}')

num = change
for idx in reversed(range(right_index + 1)):
if coins[idx] > num:
#print(f'coins[idx] = {coins[idx]} and num = {num}')
continue
#print(f'idx = {idx}')
num = num - coins[idx]
#print(f'num = {num}')
if (num in coins[0:idx-1] or num == 0) and idx != 0:
#print(f'Setting num = {num}')
num = 0
break
if num != 0:
return change
return max_amount + 1



if __name__ == '__main__':
coins = [5, 7, 1, 1, 2, 3, 22]
#coins = [1, 1, 1, 1, 1]
print(nonConstructibleChange(coins))

最新更新