Last active
April 12, 2022 10:55
-
-
Save kishkash555/020ede77fff9c2849c20eb175382a365 to your computer and use it in GitHub Desktop.
summarize a string in 3 different ways
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from itertools import groupby | |
import numpy as np | |
def summarize_string1(s): | |
if not s: | |
return [] | |
return [(0,s[0])]+[(i, c) for (i, (c, pc)) in enumerate(zip(s[1:],s),1) if c != pc] | |
def summarize_string2(s): | |
result = [] | |
for letter, group in groupby(enumerate(s),lambda x: x[1]): | |
result.append(next(group)) | |
return result | |
def summarize_string3(s): | |
str_arr = np.array(list(s.encode('ascii'))) | |
loc = np.diff(str_arr,prepend=0).nonzero()[0] | |
return [(i, s[i]) for i in loc] | |
# summarize_string('hhhhhhhaaaaaaaabbbbbbbvvvvvaaaahhhh') | |
# [(0, 'h'), (7, 'a'), (15, 'b'), (22, 'v'), (27, 'a'), (31, 'h')] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment