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

Can you explain me why outpot is so?


if __name__ == '__main__':
    N = int(input())
    lst = []
    nums = []
        
    for i in range(N):
        a = input()
        temp = a.split()
        if 'insert' in temp:
            lst.insert(int(temp[1]), int(temp[2]))
        elif 'print' in temp:
            nums.append(lst)
        elif 'remove' in temp:
            del lst[lst.index(int(temp[1]))]
        elif 'append' in temp:
            lst.append(int(temp[1]))
        elif 'sort' in temp:
            lst.sort()
        elif 'pop' in temp:
            lst.pop(-1)
        elif 'reverse' in temp:
            lst = lst.reverse()
    for i in nums:
        print(i)

Input

    12

    insert 0 5

    insert 1 10

    insert 0 6

    print

    remove 6

    append 9

    append 1

    sort

    print

    pop

    reverse

    print

Output

    [9, 5, 1]

    [9, 5, 1]

    None

Expected output

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

    [6, 5, 10]

    [1, 5, 9, 10]

    [9, 5, 1]

I am doing task on HackerRank and I almost have done it, but suddenly in every loop in ‘for i in range(N)’ program add the last list three times independent on Input.

I have tried a lot of debug tests, but I can’t find mistake in my script.

>Solution :

Two things that need to change:

  1. lst.reverse() instead of lst = lst.reverse()
  2. As you are appending, removing etc. to lst, the list that you saved in nums will change with it. You need to use nums.append(lst.copy()) instead of nums.append(lst)

The full code becomes:

if __name__ == '__main__':
    N = int(input())
    lst = []
    nums = []

    for i in range(N):
        a = input()
        temp = a.split()
        if 'insert' in temp:
            lst.insert(int(temp[1]), int(temp[2]))
        elif 'print' in temp:
            nums.append(lst.copy())
        elif 'remove' in temp:
            del lst[lst.index(int(temp[1]))]
        elif 'append' in temp:
            lst.append(int(temp[1]))
        elif 'sort' in temp:
            lst.sort()
        elif 'pop' in temp:
            lst.pop(-1)
        elif 'reverse' in temp:
            lst.reverse()

    for i in nums:
        print(i)
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