【问题标题】:Unique length-3 palindromes python唯一长度为 3 的回文 python
【发布时间】:2021-08-12 22:51:44
【问题描述】:

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

例如:

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

但这仅适用于数字

所以我尝试了迭代它并获取列表的概念 长度为三并检查它是否是回文

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

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

有什么办法吗?

谢谢

【问题讨论】:

  • 您的代码只查找连续的子字符串。您的示例输出有 aaa,它不是连续的。
  • @Barmar 那么,我该怎么办?
  • 遍历字符串以获取回文的第一个字符。然后检查字符串后面是否有匹配的字符。然后,您可以从这 2 个字符和它们之间的每个字符组成一个回文。

标签: python palindrome


【解决方案1】:

我不能 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 配方,但我认为这可行。

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

Edit2:为了使它等同于 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))

【讨论】:

    【解决方案2】:

    怎么样:

    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
    

    编辑 - combinations 比 permutations 好得多。
    编辑 - 忘了length。

    【讨论】:

    • 漂亮干净,我喜欢!值得研究这个和我的答案以了解发生了什么。在我的步骤中,这些步骤是分开的,这是将它们组合成一个表达式的非常好的方法。
    • 对于三个字母的字谜,我会坚持我的方式,但如果任务是针对 N 字母,那么你的方式肯定是要走的。
    猜你喜欢
    • 2014-02-18
    • 1970-01-01
    • 2019-03-26
    • 2017-01-14
    • 1970-01-01
    • 1970-01-01
    • 2023-02-13
    • 2022-01-21
    • 1970-01-01
    相关资源
    最近更新 更多