改进 Python 回文代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19368509/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Improving Python Palindrome code
提问by steve
So I recently implemented a code that checks a word to see if it's a palindrome.
所以我最近实现了一个代码来检查一个单词是否是回文。
def isPalindrome():
string = input('Enter a string: ')
string1 = string[::-1]
if string[0] == string[(len(string)-1)] and string[1:(len(string)-2)] == string1[1:(len(string)-2)]:
print('It is a palindrome')
else:
print('It is not a palindrome')
isPalindrome()
I was wondering if anyone could give me tips on simplifying the code.
我想知道是否有人可以给我简化代码的提示。
Edit - If I were to make the function an iterative function with the statements string == string1
, how would I stop the endless while loop? Would I need a count to stop the while loop?
编辑 - 如果我要使函数成为带有 statements 的迭代函数string == string1
,我将如何停止无限的 while 循环?我需要计数来停止 while 循环吗?
采纳答案by TerryA
No need for such complex conditional. You already have a reversed string (string[::-1]
).
不需要这么复杂的条件。您已经有一个反转字符串 ( string[::-1]
)。
All you need to do is this:
您需要做的就是:
def isPalindrome():
string1 = input('Enter a string: ')
string2 = string1[::-1]
if string1 == string2:
return 'It is a palindrome'
return 'It is not a palindrome'
isPalindrome()
(by the way don't use string
as a variable name. That's the name of a built-in module)
(顺便说一句,不要string
用作变量名。那是内置模块的名称)
It's better to returnthe strings instead of printing them. That way your function will not return None
(preventing some stuff that could happen later)
最好返回字符串而不是打印它们。这样你的功能就不会return None
(防止一些可能在以后发生的事情)
回答by Games Brainiac
You can do it in a one liner:
您可以在一个班轮中做到这一点:
return "Is a palindrome" if string == string[::-1] else "Not a palindrome"
Sample script:
示例脚本:
>>> string = "stanleyyelnats"
>>> print "Is a Palindrome" if string == string[::-1] else "Not a palindrome"
>>> Is a Palindrome
You can also do this (although its slower):
你也可以这样做(虽然它更慢):
print "Is a Palindrome" if string == ''.join(reversed(string)) else "Not a palindrome"
Also, use raw_input
and not input
. Because input
will be evaluated. Let me show you an example:
另外,使用raw_input
而不是input
。因为input
会被评价。让我给你看一个例子:
Script
脚本
inp = input("Evaluate ")
print inp
Run
跑
Evaluate "cheese" + "cake"
cheesecake
回答by James Sapam
Please check this algorithm,
请检查这个算法,
def is_palindrome(n):
m = len(n)/2
for i in range(m):
j = i + 1
if n[i] != n[-j]:
return False
return True
print is_palindrome('malayayalam')
回答by user2109202
So, I just got into learning python and I have been trying to these exercises, #8. Though I see that a lot of these answers are creating a new reverse string(which adds a memory overhead) and comparing both strings, I thought I could utilize lesser memory by doing this:
所以,我刚开始学习 python,我一直在尝试这些练习,#8。虽然我看到很多这些答案正在创建一个新的反向字符串(这会增加内存开销)并比较两个字符串,但我认为我可以通过这样做来利用更少的内存:
def is_palindrome(s):
l=len(s)
list_s=list(s)
for i in range(0,l):
if(list_s[i] !=list_s[l-i-1]):
return False
else:
return True
You can use a print statement to verify. All I am doing is comparing the first index to the last and the second index to the second last and so on. Hope that helps.
您可以使用打印语句进行验证。我所做的就是将第一个索引与最后一个索引进行比较,将第二个索引与倒数第二个索引进行比较,依此类推。希望有帮助。
回答by gogasca
Check Counter from collections
从集合中检查计数器
from collections import Counter
def is_palindrome(letters):
return len([v for v in Counter(letters).values() if v % 2]) <= 1
回答by saravanan
Here is another solution I came up with:
这是我想出的另一个解决方案:
###Piece of code to find the palindrome####
def palindrome():
Palindromee = input("Enter the palindrome \t:")
index = 0
length = len(Palindromee)
while index < length:
if Palindromee[0] == Palindromee[-1] :
index +=1
print ("Palindrome worked as expected")
palindrome()
回答by doe-eyed-
Simple way to write palindrome
写回文的简单方法
a=raw_input("Enter the string : ") # Ask user input
b= list(a) # convert the input into a list
print list(a)
b.reverse() # reverse function to reverse the
# elements of a list
print b
if list(a) == b: # comparing the list of input with b
print("It is a palindrome")
else:
print("It is not a palindrome")
回答by benlegendj
you can as well try this
你也可以试试这个
def palindrome(str1):
return str1==str1[::-1]
print(palindrome(str1)
the answer above returns a boolean according to the string given if it is a palindrome prints true else false
上面的答案根据给定的字符串返回一个布尔值,如果它是回文则打印为真否则为假
回答by suma
we could use reverse String function to verify Palindrome:
我们可以使用反向字符串函数来验证回文:
def palindrome(s):
str=s[::-1]
if s==str:
return True
else:
return False
palindrome('madam')
回答by suma
Here is a simple solution in just 1 LINE.plandrom = lambda string: True if string == string[::-1] else False
这是仅 1 LINE 的简单解决方案。plandrom = lambda string: True if string == string[::-1] else False