如何使用 Python 逻辑检查回文
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17331290/
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
How to check for palindrome using Python logic
提问by DrOnline
I'm trying to check for a palindrome with Python. The code I have is very for
-loop intensive.
我正在尝试使用 Python 检查回文。我拥有的代码是非常for
循环密集的。
And it seems to me the biggest mistake people do when going from C to Python is trying to implement C logic using Python, which makes things run slowly, and it's just not making the most of the language.
在我看来,人们在从 C 到 Python 的过程中犯的最大错误是尝试使用 Python 实现 C 逻辑,这会导致运行缓慢,而且没有充分利用该语言。
I see on thiswebsite. Search for "C-style for", that Python doesn't have C-style for loops. Might be outdated, but I interpret it to mean Python has its own methods for this.
我在这个网站上看到的。搜索“C-style for”,Python 没有 C-style for 循环。可能已经过时,但我将其解释为 Python 对此有自己的方法。
I've tried looking around, I can't find much up to date (Python 3) advice for this. How can I solve a palindrome challenge in Python, without using the for loop?
我试过环顾四周,我找不到很多最新的(Python 3)建议。如何在不使用 for 循环的情况下解决 Python 中的回文挑战?
I've done this in C in class, but I want to do it in Python, on a personal basis. The problem is from the Euler Project, great site By the way,.
我在课堂上用 C 完成了这个,但我想在个人基础上用 Python 完成。问题来自欧拉项目,很棒的网站顺便说一句,。
def isPalindrome(n):
lst = [int(n) for n in str(n)]
l=len(lst)
if l==0 || l==1:
return True
elif len(lst)%2==0:
for k in range (l)
#####
else:
while (k<=((l-1)/2)):
if (list[]):
#####
for i in range (999, 100, -1):
for j in range (999,100, -1):
if isPalindrome(i*j):
print(i*j)
break
I'm missing a lot of code here. The five hashes are just reminders for myself.
我在这里遗漏了很多代码。这五个哈希值只是对我自己的提醒。
Concrete questions:
具体问题:
In C, I would make a for loop comparing index 0 to index max, and then index 0+1 with max-1, until something something. How to best do this in Python?
My for loop (in in range (999, 100, -1), is this a bad way to do it in Python?
Does anybody have any good advice, or good websites, or resources for people in my position? I'm not a programmer, I don't aspire to be one, I just want to learn enough so that when I write my bachelor's degree thesis (electrical engineering), I don't have to simultaneously LEARN an applicable programming language while trying to obtain good results in the project. "How to go from basic C to great application of Python", that sort of thing.
Any specific bits of code to make a great solution to this problem would also be appreciated, I need to learn good algorithms.. I am envisioning 3 situations. If the value is zero or single digit, if it is of odd length, and if it is of even length. I was planning to write for loops...
在 C 中,我会做一个 for 循环,比较索引 0 和索引最大值,然后用 max-1 索引 0+1,直到出现某些东西。如何在 Python 中最好地做到这一点?
我的 for 循环(在 (999, 100, -1) 范围内),这是在 Python 中执行此操作的糟糕方法吗?
有没有人对我的职位有任何好的建议、好的网站或资源?我不是程序员,我不渴望成为程序员,我只是想学得足够多,这样当我写学士学位论文(电气工程)时,我不必在尝试的同时学习适用的编程语言以在项目中取得良好的效果。“如何从基本的 C 语言到出色的 Python 应用程序”,诸如此类。
任何可以很好地解决这个问题的特定代码位也将不胜感激,我需要学习好的算法..我设想了 3 种情况。如果该值为零或一位数,如果它是奇数长度,如果它是偶数长度。我打算写for循环......
PS: The problem is: Find the highest value product of two 3 digit integers that is also a palindrome.
PS:问题是:求两个也是回文的3位整数的最高值乘积。
采纳答案by óscar López
A pythonic way to determine if a given value is a palindrome:
一种确定给定值是否为回文的pythonic方法:
str(n) == str(n)[::-1]
Explanation:
解释:
- We're checking if the string representation of
n
equals the inverted string representation ofn
- The
[::-1]
slice takes care of inverting the string - After that, we compare for equality using
==
- 我们正在检查 的字符串表示是否
n
等于的反转字符串表示n
- 在
[::-1]
片采用反相字符串的护理 - 之后,我们使用
==
回答by jh314
The awesome part of python is the things you can do with it. You don't have to use indexes for strings.
python 最棒的部分是你可以用它做的事情。您不必为字符串使用索引。
The following will work (using slices)
以下将起作用(使用切片)
def palindrome(n):
return n == n[::-1]
What it does is simply reverses n, and checks if they are equal. n[::-1]
reverses n (the -1 means to decrement)
它所做的只是简单地反转 n,并检查它们是否相等。 n[::-1]
反转 n(-1 表示递减)
"2) My for loop (in in range (999, 100, -1), is this a bad way to do it in Python?"
“2)我的 for 循环(在 (999, 100, -1) 范围内,这是在 Python 中执行此操作的糟糕方法吗?)
Regarding the above, you want to use xrange
instead of range (because range will create an actual list, while xrange is a fast generator)
关于上述,您想使用xrange
而不是范围(因为范围将创建一个实际列表,而 xrange 是一个快速生成器)
My opinions on question 3
我对问题3的看法
I learned C before Python, and I just read the docs, and played around with it using the console. (and by doing Project Euler problems as well :)
我在 Python 之前学过 C,我只是阅读文档,然后使用控制台玩弄它。(以及通过执行 Project Euler 问题:)
回答by RichieHindle
An alternative to the rather unintuitive [::-1]
syntax is this:
相当不直观的[::-1]
语法的替代方法是:
>>> test = "abcba"
>>> test == ''.join(reversed(test))
True
The reversed
function returns a reversed sequence of the characters in test
.
该reversed
函数返回 中字符的反向序列test
。
''.join()
joins those characters together again with nothing in between.
''.join()
将这些字符再次连接在一起,中间没有任何内容。
回答by alxxas
Here is an example that takes a user's input and checks if the input is a palindrome:
这是一个接受用户输入并检查输入是否为回文的示例:
name = input("Write your word here: ")
input("Press <enter> to check if the word is a palindrome.")
if str(name) == str(name)[::-1]:
print("True")
else:
print("False")
However, there is no need to even set up the if
/else
statement. You can directly print the result of the logical comparison, as shown here:
但是,甚至不需要设置if
/else
语句。可以直接打印逻辑比较的结果,如下所示:
name = input("Write your word here: ")
input("Press <enter> to check if the word is a palindrome.")
print(str(name) == str(name)[::-1])
回答by Ganesh Pandey
Below the code will print 0if it is Palindromeelse it will print -1
如果是回文,代码下方将打印0,否则将打印-1
Optimized Code
优化代码
word = "nepalapen"
is_palindrome = word.find(word[::-1])
print is_palindrome
Output:0
输出:0
word = "nepalapend"
is_palindrome = word.find(word[::-1])
print is_palindrome
Output:-1
输出:-1
Explaination:
说明:
when searching the string the value that is returned is the value of the location that the string starts at.
搜索字符串时,返回的值是字符串开始位置的值。
So when you do word.find(word[::-1])
it finds nepalapen
at location 0
and [::-1]
reverses nepalapen
and it still is nepalapen
at location 0
so 0
is returned.
因此,当您执行word.find(word[::-1])
它时,它会nepalapen
在 location 处找到0
并[::-1]
反转nepalapen
,但它仍然nepalapen
在 location 处,0
因此0
返回。
Now when we search for nepalapend
and then reverse nepalapend
to dnepalapen
it renders a FALSE
statement nepalapend
was reversed to dnepalapen
causing the search to fail to find nepalapend
resulting in a value of -1
which indicates string not found.
现在,当我们搜索nepalapend
,然后扭转nepalapend
到dnepalapen
它呈现一个FALSE
声明nepalapend
被逆转dnepalapen
导致搜索无法找到nepalapend
导致价值的-1
指示字符串没有找到。
Another method print trueif palindromeelse print false
如果回文,另一种方法打印真,否则打印假
word = "nepalapen"
print(word[::-1]==word[::1])
output:TRUE
输出:真
回答by Chaker
Here a case insensitivefunction since all those solutions above are case sensitive.
这是一个不区分大小写的函数,因为上述所有解决方案都区分大小写。
def Palindrome(string):
return (string.upper() == string.upper()[::-1])
This function will return a booleanvalue.
此函数将返回一个布尔值。
回答by bausi2k
doing the Watterloo course for python, the same questions is raised as a "Lesseon" find the info here:
为 python 做 Watterloo 课程,在“课程”中提出了同样的问题,在这里找到信息:
http://cscircles.cemc.uwaterloo.ca/13-lists/
http://cscircles.cemc.uwaterloo.ca/13-lists/
being a novice i solved the problem the following way:
作为新手,我通过以下方式解决了这个问题:
def isPalindrome(S):
pali = True
for i in range (0, len(S) // 2):
if S[i] == S[(i * -1) - 1] and pali is True:
pali = True
else:
pali = False
print(pali)
return pali
The function is called isPalindrome(S)and requires a string "S". The return value is by default TRUE, to have the initial check on the first if statement.
该函数称为isPalindrome(S)并且需要一个字符串"S"。返回值默认为TRUE,对第一个 if 语句进行初始检查。
After that, the for loop runs half the string length to check if the character from string "S"at the position "i"is the same at from the front and from the back. If once this is not the case, the function stops, prints out FALSE and returns false.
之后,for 循环运行字符串长度的一半,以检查字符串“S”中位于“i”位置的字符从前面和后面看是否相同。如果一旦不是这种情况,该函数将停止,打印出 FALSE 并返回 false。
Cheers.kg
干杯.kg
回答by sanster9292
I know that this question was answered a while ago and i appologize for the intrusion. However,I was working on a way of doing this in python as well and i just thought that i would share the way that i did it in is as follows,
我知道这个问题是在不久前回答的,我为这次入侵表示歉意。但是,我也在研究一种在 python 中执行此操作的方法,我只是想我会分享我的方法如下,
word = 'aibohphobia'
word_rev = reversed(word)
def is_palindrome(word):
if list(word) == list(word_rev):
print'True, it is a palindrome'
else:
print'False, this is''t a plindrome'
is_palindrome(word)
回答by tkhanna
#!/usr/bin/python
str = raw_input("Enter a string ")
print "String entered above is %s" %str
strlist = [x for x in str ]
print "Strlist is %s" %strlist
strrev = list(reversed(strlist))
print "Strrev is %s" %strrev
if strlist == strrev :
print "String is palindrome"
else :
print "String is not palindrome"
回答by ufukomer
If the string has an uppercase or non-alphabetic character then the function converts all characters to lowercase and removes all non-alphabetic characters using regex finally it applies palindrome check recursively:
如果字符串具有大写或非字母字符,则该函数将所有字符转换为小写,并使用正则表达式删除所有非字母字符,最后它递归地应用回文检查:
import re
rules = [
lambda s: any(x.isupper() for x in s),
lambda s: not s.isalpha()
]
def is_palindrome(s):
if any(rule(s) for rule in rules):
s = re.sub(r'[^\w]', '', s).lower()
if len(s) < 2:
return True
if s[0] != s[-1]:
return False
return is_palindrome(s[1:-1])
string = 'Are we not drawn onward, we few, drawn onward to new era?'
print(is_palindrome(string))
the output is True
for the input above.
输出True
用于上面的输入。