独特的长度为3的回文蟒蛇

我有这个问题,你必须找到所有长度为三个的 回文并打印有多少。

例如:

aabca

输出:

3
aba
aaa
aca

我已经知道如何使用我在下面的网络上找到的代码来获取数量的数量:

res = 0
unq_str = set(s)
for ch in unq_str:
    st = s.find(ch)
    ed = s.rfind(ch)
    if st<ed:
        res+=len(set(s[st+1:ed]))

return res

但这仅适用于 num

所以我尝试了一个概念,你遍历它并获取长度为 3 的列表并检查它是否是回文

for x in range(len(input1)):
    if not x < 3:
        Str1 = input1[x-3:x]

但后来我停了下来,因为它不适合任何类型的组合

有没有办法做到这一点?

谢谢

回答

我不是 100% 确定这是正确的,但希望它能让你走上正确的轨道。

import itertools

input = "aabca"
palindromes = set() # use a set to ensure no duplicates

# iterate over all combinates of length 3
for t in itertools.combinations(input, 3):
    # is this a palindrome? If so save
    if t == tuple(reversed(t)):
        palindromes.add(''.join(t))

# output results
print(palindromes)
print(len(palindromes))

可能有一个不会生成重复项的 itertools 配方,但我认为这是可行的。

编辑:使用连接会产生一组字符串而不是字符串字符。

编辑 2:要使其等同于 keithpjolly 的回答:

import itertools

input = "aabca"
palindromes = set() # use a set to ensure no duplicates

# iterate over all combinates of length 3
for a,b,c in itertools.combinations(input, 3):
    # is this a palindrome? If so save
    if a == c:
        palindromes.add(''.join((a,b,c)))


# output results
print(palindromes)
print(len(palindromes))


回答

怎么样:

from itertools import combinations
s = 'aabca'
p = set([''.join([a,b,c]) for a,b,c in combinations(s, 3) if a == c])
print(p)
print(len(p))

输出:

{'aaa', 'aba', 'aca'}
3

编辑 -combinationspermutations.
编辑 - 忘记了length.


以上是独特的长度为3的回文蟒蛇的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>