Python中的平原。

如何在Python中实现Plaindromes。

# 回答1

回文是一个短语、一个单词或一个前后读相同的序列。一个这样的例子就是pip!护士跑步就是这样一个例子。

选择 | 换行 | 行号
  1. >>> def isPalindrome(string):
  2.       left,right=0,len(string)-1
  3.       while right>=left:
  4.               if not string[left]==string[right]:
  5.                        return False
  6.               left+=1;right-=1
  7.               return True
  8. <span style="font-weight: 400">>>> isPalindrome('redrum murder')</span>
  9. True
  10.  
  11. >>> isPalindrome('CC.')
  12. False
  13.  
  14. Well, there are other ways to do this too. Let’s try using an iterator.
  15.  
  16. >>> def isPalindrome(string):
  17.       left,right=iter(string),iter(string[::-1])
  18.       i=0
  19.       while i<len(string)/2:
  20.              if next(left)!=next(right):
  21.                       return False
  22.              i+=1
  23.              return True
  24. >>> isPalindrome('redrum murder')
  25. True
  26.  
  27. >>> isPalindrome('CC.')
  28. False
  29.  
  30. >>> isPalindrome('CCC.')
  31. False
  32.  
  33. >>> isPalindrome('CCC')
  34. True
  35.  
  36.  

标签: python

添加新评论