简体   繁体   English

统计一个字符串在该字符串的反序position中出现的次数

[英]Count the number of times a string appears in the reverse position of the string

I am trying to figure out a way that you can count how many times a letter appears in the exact opposite position. For example:我正在尝试找出一种方法,您可以计算一个字母在完全相反的 position 中出现了多少次。例如:

word = 'ABXCEEVHBA' --> The correct output give me 3 because A is first and last. word = 'ABXCEEVHBA' --> 正确的 output 给我 3 因为 A 是第一个也是最后一个。 B is second and second from last and so forth. B 是第二个,倒数第二个,依此类推。

I have found an answer that gives me the correct result but I was wondering if there is a more elegant way to do this ideally with no modules.我找到了一个给出正确结果的答案,但我想知道是否有更优雅的方法可以在没有模块的情况下理想地做到这一点。

word = 'ABXCEEVHBA'
reverse = ''.join(reversed(word))

sum =0
for i in range(len(word)):
    if word[i]==reverse[i]:
        sum+=1

print(int(sum/2))

Believe this shall do it:相信这会做到:

>>> count = 0
>>> for i in range(len(word)//2):  # meet half-way.
    if word[i] == word[~i]:
        count += 1

        
>>> count
3

You can do it with zip by combining the string with the inverse of itself:你可以用 zip 把字符串和它本身的反相组合起来:

sum(a==b for a,b in zip(word,reversed(word)))//2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM