+ 1
Python question w.r.t arrays
What changes needs to be done to make the code below error-free? def fun(*a) i=0 for v in a: if v==0: arg[i]=1 i+=1 return a print (fun(5,2,0,4,0)) Credit to Javier.I. Rivera R. for the question :)
3 Answers
+ 3
You could do it like this (although it's unnecessarily lengthy):
def fun(*a):
arg = []
i=0
for v in a:
if v==0:
arg.append(1)
else:
arg.append(a[i])
i+=1
return arg
print (fun(5,2,0,4,0))
The main problems:
1.) Colon was missing;
2.) Tuple values can't be changed.
A shorter way:
def fun(*a):
return tuple(n if n != 0 else 1 for n in a)
print (fun(5,2,0,4,0))
+ 1
The purpose of the function is to change all 0s in the array to 1s.
0
What is the purpose of the function? Without knowing that, how would it be possible to help?