Find the letters in a python list that follow each other most frequently -
Find the letters in a python list that follow each other most frequently -
i have python list one:
list = [s,b,s,d,h,a,h,e,h,a] is there easy way find out letters follow each other frequently.
in list:
h,a = 2x it cool have finish table of letters follow how often. not sure how tackle this
b d e s 1 1 h 2 1
use collections.counter() , feed letter pairs:
from collections import counter pair_counts = counter(zip(list, list[1:])) demo:
>>> collections import counter >>> list = ['s', 'b' , 's', 'd', 'h', 'a', 'h', 'e', 'h', 'a'] >>> pair_counts = counter(zip(list, list[1:])) >>> pair_counts.most_common() [(('h', 'a'), 2), (('d', 'h'), 1), (('s', 'b'), 1), (('s', 'd'), 1), (('b', 's'), 1), (('h', 'e'), 1), (('a', 'h'), 1), (('e', 'h'), 1)] >>> pair_counts.most_common(1) [(('h', 'a'), 2)] the counter can used produce table:
values = sorted(set(list)) colwidth = len(str(pair_counts.most_common(1)[0][1])) row_template = '{} ' + ' '.join(['{:>{colwidth}}'] * len(values)) print row_template.format(' ', colwidth=colwidth, *values) in values: print row_template.format(a, colwidth=colwidth, *( pair_counts.get((a, b), '') b in values)) which produces:
b d e h s 1 b 1 d 1 e 1 h 2 1 s 1 1 python
Comments
Post a Comment