开发者

How to make a function that counts how many times each element is equal to 2 elements to its right

开发者 https://www.devze.com 2023-04-12 11:37 出处:网络
I know i need to use a list comprehension but for the life of me I cannot figure out what would be the correct way to denote this. An example of this running right would befor \"evening\" the output b

I know i need to use a list comprehension but for the life of me I cannot figure out what would be the correct way to denote this. An example of this running right would be for "evening" the output being 2, once 开发者_如何学运维 for 'e' and once for 'n'


The list comprehension gives the letters that have the same letter two places to the right. We simply take the length of the resulting list:

s = "evening"
ans = len([x for x in xrange(len(s)-2) if s[x] == s[x+2]])
print ans


s='evening'
print len([x for x,y in zip(s, s[2:]) if x==y])

Output:

2


I would love to see someone more expert than me turn this into a lc but my basic sollution would be

zz='evening'
for numb, letter in enumerate(zz):
if numb+2==len(zz):
    break
if letter==zz[numb+2]:
    count+=1

Well after seeing Mike's answer and thinking about it how about this if the input is a list

foo = ['e', 'v', 'e', 'n', 'i', 'n', 'g']
new=[item for numb, item in enumerate(foo[0:-2]) if item==foo[numb+2]]
answer=len(new)

silly me, I can also work with a string and I think this is still cleaner

testString='evening'
new=[letter for numb, letter in enumerate(testString[0:-2]) if letter==testString[numb+2]]
ans=len(new)
0

精彩评论

暂无评论...
验证码 换一张
取 消