I have the following numbers in an array: 1 2 7 4 6 7 8 How do I insert the next number of each even number after this one? so I am left with the following: 12 3 74 5 6 7 78 9 .
def par(a):
n2=[]
for i in range(len(n)):
if a[i] % 2 != 0:
n2.append(a[i])
else:
n2.insert(a[i]+1)
If it is an array with numbers, it is enough to go through the array and:
1- The current element is inserted, yes or yes, in the resulting array:
n2.append(elem)
2- If the current element is even (
elem % 2 == 0
), then insert:n2.append(elem+1)
. You don't need aelse
.Proof:
Your code has some bugs (apart from the variable
n
not being defined inside the function, I assume you meant variablea
).n2
you are buildinginsert()
requires two parameters, and you only pass one to it. You also have to pass it where you want to put it on the list. But you don't really need it, because you put it at the end, for what it's worth usingappend()
Therefore the corrections are:
Also you can improve the for loop by iterating through the values instead of the indices, it's more "pythonic":
If the function instead of a list receives a string, such as "1274678", the loop does the same, but you must convert each digit to an integer before checking whether it is odd or even. The list you build as a result can be converted back to a string, converting each element to a string and concatenating them all with
"".join()
. It would then be like this:And now you could use it like this:
to return the string "12374567789"