简体   繁体   中英

What is wrong with the code I wrote?

def insert(lst, idx, elem):
    lst = lst[:idx] + [elem] + lst[idx:]

list1 = [0, 1, 2, 3, 4, 6, 7]
insert(list1, 5, 5)

list2 = ['0', '1', '0']
insert(list2, 0, '1')

for example, list1 should be [0, 1, 2, 3, 4, 5, 6, 7]
for example, list2 should be ['1', '0', '1', '0']
Edit: for example, insert([1, 2, 3], 1, 0) should be None

What is wrong with my code? What should be the correct answer?

I have been getting:
list1 [0, 1, 2, 3, 4, 6, 7]
list2 ['0', '1', '0']

You should return the value of lst :

def insert(lst, idx, elem):
    lst = lst[:idx] + [elem] + lst[idx:]
    return lst

list1 = [0, 1, 2, 3, 4, 6, 7]
x = insert(list1, 5, 5)

list2 = ['0', '1', '0']
y = insert(list2, 0, '1')

print(x)
print(y)

Result:

[0, 1, 2, 3, 4, 5, 6, 7]
['1', '0', '1', '0']

Hi I assume that this question wants you to modify the list in place.

When you use slicing, there will actually be new copies created instead of modifying the list in place. Hence, when you try to call insert() and print(x) you will get [0, 1, 2, 3, 4, 6, 7]

What you can do is to create a copy of the array using [:] --> lst[:] = lst[:idx] + [elem] + lst[idx:]

you don't need to return lst as the test case actually tests for whether lst is original array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM