Write a function that accepts a list. The function should change the element of a list with a max value on its right side. The last element of a list should be changed to -1.
Input: [17, 18, 5, 4, 6, 1]
Output: [18, 6, 6, 6, 1,−1]
I was able to do the first part but I can’t seem to change the value of the last element to -1.
def list_change(lista):
for i in range(0, len(lista)):
if i == (len(lista) - 1):
x = 0 - 1
lista[i] = lista[x]
else:
tmax = -100000000
for j in range(i + 1, len(lista)):
if lista[j] > tmax:
lista[i] = lista[j]
tmax = lista[j]
print(lista)
list_change([17, 18, 5, 4, 6, 1])
>Solution :
It is easy, change the last element using its index –
def list_change(lista):
for i in range(0, len(lista)):
if i == (len(lista) - 1):
x = 0 - 1
lista[i] = lista[x]
else:
tmax = -100000000
for j in range(i + 1, len(lista)):
if lista[j] > tmax:
lista[i] = lista[j]
tmax = lista[j]
lista[-1] = -1 # Get the last element and change it.
print(lista)
list_change([17, 18, 5, 4, 6, 1])