Python finding index of elements with certain conditions -
this question has answer here:
i have following string:
array = "tqtdtqd"
for each d in array, there anyway know how many consecutive t's or d's before , after each d same letter right before each d. 1st d, letter right before t, want find how many consecutive t's before , after 1st d. 2nd d, letter right before q, want find # of consecutive q's before , after 2nd d.
for instance, 1st d, there 1 t before d , 1 t after showing until there q. (e.g: 1st d, "tdt")
for 2nd d, there 1 consecutive q before or no q after
i did start following python codes find positions of each t,q,d:
get_indexes = lambda x, xs: [i (y, i) in zip(xs, range(len(xs))) if x == y] t_position = get_indexes("t",array) q_position = get_indexes("q",array) d_position = get_indexes("d",array)
and tried find out t's before each d.
for each in range(0,len(d_position)): rightbefored = array[d_position[each]-1] numberoft = [] eachofallbefore in reversed(range(0,d_position[each])): if array[eachofallbefore] ==rightbefored: numberoft.append(array[eachofallbefore]) print (numberoft)
but results these 2 d's 1st d:["t","t"], 2nd d: ["q","q"], seems prints out t or q's before each d,
- i wondering if add check point stop loop once consecutive t/q's end.
- also wonder if use same method finding consecutive t/q's after each d.
many thx!
i think works:
import re def sequences(s): xdx = re.findall(r"['q']+['d']['q']*|['t']+['d']['t']*", s) i, d_group in enumerate(xdx): before, after = d_group.split('d') print("for d{0} there {1}({2})s before , {3}({2})s after".format(i+1, len(before), before[0], len(after))) if __name__ == "__main__": sequences('qqqdqqtqdqqtdtdqq')
Comments
Post a Comment