Why does my code only duplicate the first zero and not the others?
def addzeros(a):
c = a.count(0)
while c>0:
for i in a:
if a[i] == 0:
a.insert(a[i 1],0)
return a
print(addzeros([1,0,2,0,7]))
CodePudding user response:
Because a function may only return
once; once it returns, the function call is over. Also note that it is highly discouraged to alter a list while iterating through it.
Try defining an empty list instead and populating it while iterating through the old list:
def addzeros(a):
c = a.count(0)
b = []
for i in a:
if i == 0:
b.extend((0, 0))
else:
b.append(i)
return b
print(addzeros([1,0,2,0,7]))
Output:
[1, 0, 0, 2, 0, 0, 7]
CodePudding user response:
I'm not a python user, but it appears that your return statement is within your loop. Therefore, you will never loop through the whole array as it will return on its first usage. If this is wrong let me know I will delete, like I said I am not too familiar with python.
CodePudding user response:
You could also try this way - working from the back to the front:
[Note] this works as it changes happening in-place, while you iterating the list. If that's not what you want, you can make a separate copy too. BTW, this comes late, and doesn't directly answer OP question - because earlier post did answer it.
def add_zeros(nums):
for i in range(len(nums)-1, -1, -1):
if nums[i] == 0:
nums.insert(i, 0)
Running:
>>> add_zeros(nums)
[1, 0, 0, 2, 0, 0, 7]