Python: search longest palindromes within a word and palindromes within a word/string

后端 未结 15 1773
你的背包
你的背包 2020-12-03 09:38

So here is a code i have written to find palindromes within a word (To check if there are palindromes within a word including the word itself) Condition: spaces inbetween ch

相关标签:
15条回答
  • 2020-12-03 10:11
    inputStr = "madammmdd"
    outStr = ""
    uniqStr = "".join(set(inputStr))
    flag = False
    for key in uniqStr:
       val = inputStr.count(key)
       if val % 2 !=0:
          if not flag:
             outStr = outStr[:len(outStr)/2]+key+outStr[len(outStr)/2:]
             flag=True
          val-=1
       outStr=key*(val/2)+outStr+key*(val/2)
    print outStr
    
    0 讨论(0)
  • 2020-12-03 10:13
    def longestPalindrome(s):
            temp = ""
            for i in range(len(s)):
                for j in range(len(s)-1,i-1,-1):
                    if s[i] == s[j]:
                        m = s[i:j+1]
                        if m == m[::-1]:
                            if len(temp) <= len(m):
                                temp = m
            return temp
    
    0 讨论(0)
  • 2020-12-03 10:15

    s='stresseddesserts'
    out1=[]
    def substring(x):
        for i in range(len(x)):
            a=x[i:]
            b=x[:-i]
            out1.append(a)
            out1.append(b)
            
        return out1
    
    for i in range(len(s)):
        substring(s[i:])    
    final=set([item for item in out1 if len(item)>2])
    final
    palind={item:len(item) for item in final if item==item[::-1]}
    print(palind)
    sorted(palind.items(),reverse=True, key=lambda x: x[1])[0]

    {'tresseddessert': 14, 'seddes': 6, 'esseddesse': 10, 'esse': 4, 'stresseddesserts': 16, 'resseddesser': 12, 'edde': 4, 'sseddess': 8}

    ('stresseddesserts', 16)

    0 讨论(0)
提交回复
热议问题