【问题标题】:IndexError when checking if input is palindrome using while loop使用while循环检查输入是否为回文时的IndexError
【发布时间】:2013-02-13 19:02:26
【问题描述】:

我想知道如何使用 Python 检查输入是否为带有 while 循环的回文。

谢谢:

我试过了

i = 0
n = len(msg_list)

while i < n:
    palindrome = msg_list[i]
    if palindrome == msg_list[-1]:
        print("Palindrome? True")
        msg_list.pop(-1)
    else:
        print("Palindrome? False")
    i=i+1

但最后我收到一条错误消息,指出列表索引超出范围

【问题讨论】:

标签: python loops while-loop palindrome


【解决方案1】:

您不需要迭代到最后,而只需要迭代到中间字符。并在反向计数时将每个字符与同一索引处的字符进行比较:

s = "abcca"
length = len(s)
i = 0

while i < length / 2 + 1:
    if s[i] != s[-i - 1]:
        print "Not Palindrome"
        break
    i += 1
else:
    print "Palidrome"

当循环在没有任何break 的情况下完成其迭代时,将执行while 循环的一部分else


或者,如果您可以使用除while 循环之外的任何其他内容,那么此任务就是Python 中的single 行:

if s == s[::-1]: 
    print "Palindrome"

哦,变成了两行。

【讨论】:

    【解决方案2】:

    有一个while循环

    import string
    
    palin = 'a man, a plan, a canal, panama'
    
    def testPalindrome(in_val):
        in_val = in_val.lower()
        left, right = 0, len(in_val) - 1
        while left < right:
            char_left, char_right = '#', '#'
            while char_left not in string.lowercase:
                char_left = in_val[left]
                left += 1
            while char_right not in string.lowercase:
                char_right = in_val[right]
                right -= 1
            if char_left != char_right:
                return False
        return True
    
    print testPalindrome(palin)
    

    没有

    >>> palindrome = 'a man, a plan, a canal, panama'
    >>> palindrome = palindrome.replace(',', '').replace(' ', '')
    >>> palindrome
    'amanaplanacanalpanama'
    >>> d[::-1] == d
    True
    

    【讨论】:

      【解决方案3】:

      使用reversed 的简短解决方案:

      for c, cr in s, reversed(s):
          if c != cr:
              print("Palindrome? False")
              break
      else:
          print("Palindrome? True")
      

      【讨论】:

      • 但 OP 只想要 while。 :( :( 否则它可以更短。;)
      【解决方案4】:

      使用while 循环的另一种方式。一旦两个字符不匹配,while 循环就会停止,因此它非常有效,但当然不是 Python 中最好的方法。

      def palindrome(word):
         chars_fw = list(word)
         chars_bw = list(reversed(word))
         chars_num = len(word)
         is_palindrome = True
         while chars_num:
             if chars_fw[chars_num-1] != chars_bw[chars_num-1]:
                 is_palindrome = False
                 break
             chars_num -= 1
      
         return is_palindrome 
      

      【讨论】:

        【解决方案5】:

        我想我会为仍在查看此问题的人添加另一种选择。它使用了一个 while 循环,并且相当简洁(尽管我仍然更喜欢 if word = word[::-1] 方法。

        def is_palindrome(word):    
            word = list(word.replace(' ', ''))  # remove spaces and convert to list
            # Check input   
            if len(word) == 1:
                return True
            elif len(word) == 0:
                return False
            # is it a palindrome....    
            while word[0] == word[-1]:
                word.pop(0)
                word.pop(-1)    
                if len(word) <= 1:
                    return True
            return False
        

        【讨论】:

          【解决方案6】:
          word = "quiniuq"
          pairs = zip(word,reversed(word))
          a,b = next(pairs)
          try:
              while a == b:
                  a,b = next(pairs)
              return False # we got here before exhausting pairs
          except StopIteration:
              return True # a == b was true for every pair
          

          这里使用while循环是人为的,但它会消耗整个列表并执行测试。

          如果不需要 while 循环,可以这样做:all(a == b for a,b in zip(word,reversed(word)))

          【讨论】:

            猜你喜欢
            • 2018-09-08
            • 1970-01-01
            • 1970-01-01
            • 2012-10-05
            • 1970-01-01
            • 2016-02-13
            • 2022-01-27
            • 2021-09-16
            • 2015-10-04
            相关资源
            最近更新 更多