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

后端 未结 3 825
一整个雨季
一整个雨季 2021-01-23 11:15

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

相关标签:
3条回答
  • 2021-01-23 11:24

    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
    
    0 讨论(0)
  • 2021-01-23 11:38
    s='evening'
    print len([x for x,y in zip(s, s[2:]) if x==y])
    

    Output:

    2
    
    0 讨论(0)
  • 2021-01-23 11:42

    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 讨论(0)
提交回复
热议问题