current position:Home>Python 3 interview question: give an array. If there is 0 in the array, add a 0 after 0, and the overall array length remains the same

Python 3 interview question: give an array. If there is 0 in the array, add a 0 after 0, and the overall array length remains the same

2021-08-23 06:21:57 Shanghai - youyou

Interview questions

Give an array , If there is... In the array 0, It's in 0 Add a... To the back 0, The overall array length remains unchanged , Request cannot generate new array , Can only operate under the current array Input : arr = [1, 2, 4, 0, 5, 0, 9, 6] Expected output : [1,2,4,0,0,5,0,0]

Solutions

Using recursion , Every time you find... In the list 0, Add a 0, And remove the last item , Get new arr By analogy , The first time is from 0 Position start , Next time add from 0 Continue at the rear position

def func(index:int, arr:list):
    """
     If there is... In the array 0, It's in 0 Add a... To the back 0, The overall array length remains unchanged 
    :param index: index yes a The index of 
    :param arr:  Pass in array 
    :return: func() function  index From the inserted position , Continue to recursive 
    """
    if index >= len(arr)-1:
        return arr
    for i in range(index, len(arr)):
        if arr[i] == 0:
            arr.insert(i+1, 0)  #  Insert 0
            arr.pop()           #  Remove the last one 
            return func(i+2, arr)   #  recursive 

if __name__ == '__main__':
    arr = [1, 2, 4, 0, 5, 0, 9, 6]
    print(func(0, arr))

Running results :[1, 2, 4, 0, 0, 5, 0, 0]

2021 The eighth issue of 《python Interface web automation + Test Development 》7.17 School begins on ( The course is fully upgraded !) Add quantity without price ( newly added postman, Give selenium and python Basics 2 Classes )

This article is from WeChat official account. - Learn automated testing from scratch (yoyoketang) , author : Shanghai is long

The source and reprint of the original text are detailed in the text , If there is any infringement , Please contact the [email protected] Delete .

Original publication time : 2021-08-10

Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .

copyright notice
author[Shanghai - youyou],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2021/08/20210823062154659l.html