Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to change the last list element to -1?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading