Практика - критерий истины! (с) Маркс
def func1(s):
st = []
for i in range(0,len(s)):
if s[i] != s[i-1]:
st.append(s[i])
return "".join(st)
def func2(s):
result_str = []
for (key,group) in groupby(s):
result_str.append(key)
return ''.join(result_str)
def func3(s):
return re.sub(r"(.)\1+", r"\1", s)
def func4(s):
return "".join(unique_justseen(s))
замеры времени:
In [22]: s = "".join(str(i) for i in range(10**5))
In [23]: len(s)
Out[23]: 488890
In [24]: %timeit func1(s)
135 ms ± 117 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
In [25]: %timeit func2(s)
99.7 ms ± 311 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
In [26]: %timeit func3(s)
92.6 ms ± 1.37 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
In [36]: %timeit func4(s)
107 ms ± 487 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
UPD: для более длинной строки (5.888.890 символов):
In [38]: s = "".join(str(i) for i in range(10**6))
In [42]: len(s)
Out[42]: 5888890
In [39]: %timeit func1(s)
1.67 s ± 25.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
In [40]: %timeit func2(s)
1.25 s ± 4.49 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
In [41]: %timeit func3(s)
1.18 s ± 2.32 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
In [43]: %timeit func4(s)
1.35 s ± 13.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
print(''.join(set(s)))
(.)\1+
на `\1' :)