I have a python for loop over a string, that have to decide char-by-char if the current char should stay or be removed.
Let's say I have a function fun(character,state) which receives a char, and some state parameter, and returns True if the char should be kept, and a new state. for example:
def fun(c,state):
if state%5==0:
return False, state+1
else:
return True, state+2
I have two ideas how to iterate (sequentially) over the string with this function, but I can't decide between them (or others) in terms of runtime complexity and space usage tradeoff:
Option 1:
def option1(string):
state = 0
i =0
while i<len(string):
answer, state = fun(string[i],state)
if not answer:
string = string[:i]+string[i+1:]
else:
i+=1
return string
Option 2:
def option2(string):
result = ''
state = 0
for c in string:
answer, state = fun(c,state)
if answer:
result+=c
return result
Does anyone has a better approach/ solution?
edit: some timing results:
on a long string ( 67976 chars) the results are:
- option1 - 205 ms
- option2 - 46 ms
looks like eliminating the i'th char with string[:i]+string[i+1:] is not a good idea.
len(string)every loop.joinanswer below) nearly two times faster.