from itertools import pairwise
l_h = []
l_r = []
for index, elem in enumerate("THISISTHEARHGRAYR"):
if elem == "R":
l_r.append(index)
if elem == "H":
l_h.append(index)
H = [b - a for a, b in pairwise(l_h)]
R = [b - a for a, b in pairwise(l_r)]
print(H,R)[enter image description here][1]
And I 1: https://i.sstatic.net/dCMC5.png If i run this code I get error cannot import name 'pairwise' from 'itertools'
It looks like your version of itertools does not have the pairwise
function. You can check its available functions in the docs (select Python version in the upper left corner).
I suggest creating your own implementation of pairwise
, I found this one to work well.
Code and output:
from itertools import tee
def pairwise(iterable):
a, b = tee(iterable) # Note that tee is from itertools
next(b, None)
return zip(a, b)
l_h = []
l_r = []
for index, elem in enumerate("THISISTHEARHGRAYR"):
if elem == "R":
l_r.append(index)
if elem == "H":
l_h.append(index)
# Added -1 to count letters BETWEEN duplicates
H = [ b - a - 1 for a, b in pairwise(l_h) ]
R = [ b - a - 1 for a, b in pairwise(l_r) ]
print(H, R)
outputs
[5, 3] [2, 2]
.
Also, upgrading to Python 3.10 should work (I have not tested this).