Arnoald Hagel - 8 days ago 5x

Python Question

I'm curious as to how this can be rewritten as a for loop?

`def decode (lst):`

i=0

result=[]

while i<len(lst):

result+=([lst[i]]*lst[i+1])

i+=2

return(result)

print(decode([4,6,2,1,9,5,5,2,4,2]))

Answer

Assuming that this is Python code (as it looks like) you can just specify the step in the range function.

```
def decode (lst):
result = []
#More common syntax if not using python for(i = 0; i < len(lst); i += 2):
for i in range(0, len(lst), 2):
result += ([lst[i]] * lst[i+1])
return result
print(decode([4,6,2,1,9,5,5,2,4,2]))
```

You will also want to add some error checking to make sure that your array has an even number of elements or this and your original example will fail.

Source (Stackoverflow)

Comments