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

后端 未结 3 870
一整个雨季
一整个雨季 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: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)
    

提交回复
热议问题