tag:blogger.com,1999:blog-7538277648080836914.post4884068090852231085..comments2023-09-01T08:40:57.156-07:00Comments on Doc Ernie's Adventures in the Web: Python: can you program something better or differently? Counting number of runs and occurrences of two symbols.Anonymoushttp://www.blogger.com/profile/15904737296922954023noreply@blogger.comBlogger2125tag:blogger.com,1999:blog-7538277648080836914.post-85210839205245681002010-05-14T12:36:59.282-07:002010-05-14T12:36:59.282-07:00Thanks to your elegant and shorter Python solutio,...Thanks to your elegant and shorter Python solutio, Ianalis. Itertools is one module which one needs to be more familiar with as it has quite powerful functions.Anonymoushttps://www.blogger.com/profile/15904737296922954023noreply@blogger.comtag:blogger.com,1999:blog-7538277648080836914.post-72029006725489758552010-05-14T08:45:47.935-07:002010-05-14T08:45:47.935-07:00Since this is a Python problem, using a built-in m...Since this is a Python problem, using a built-in module is valid. The code below has an added benefit of not limiting the number of symbols to two. The for loop can be removed (vectorized) by using two groupby() calls instead of one. BTW, indentation doesn't work. :(<br /><br />import itertools<br />def countruns(S):<br /> # returns number of runs, and (m,n) in string S<br /> runs = 0<br /> counts = {}<br /> for k, v in itertools.groupby(S):<br /> runs += 1<br /> counts[k] = counts.get(k, 0) + sum(1 for i in v)<br /> return runs, counts.values()<br /> <br />S = "aaaabbbbbbabababbbbbbbbbbbbbbbbbb" <br />print countruns(S)ianalishttps://www.blogger.com/profile/01773990348425956371noreply@blogger.com