python 检查回文的偶数/奇数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2095404/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 23:46:06  来源:igfitidea点击:

Check even/odd for Palindrome?

pythontestingpalindrome

提问by eozzy

Is it a good idea to check for odd/even length of a palindrome number/string? Most snippets I came across don't do this basic test. If length is even, it can't be a palindrome, no?

检查回文数/字符串的奇数/偶数长度是个好主意吗?我遇到的大多数片段都没有进行这个基本测试。如果长度是偶数,它就不可能是回文,不是吗?

if len(var) % 2 != 0:
  # could be a palindrome, continue...
else:
  break

Or is it just better (i.e faster) to start comparing the first and last numbers/letters directly?

或者直接开始比较第一个和最后一个数字/字母是否更好(即更快)?

Edit: Okay, stupid question, should've thought twice! :)

编辑:好吧,愚蠢的问题,应该三思而后行!:)

回答by TabbyCool

ABBA- an example of palindromeof four letters meaning even length.

ABBA-表示偶数长度的四个字母的回文示例。

A palindromeis a word, phrase, number, or other sequence of characterswhich reads the same backward or forward...

回文是单词,短语,数字,或其他序列的字符读取相同的向后或向前...

回答by sth

The easiest way to check for a palindrome is to simply compare the string against it's reverse:

检查回文的最简单方法是简单地将字符串与其反向进行比较:

def ispalindrome(s):
   return s == s[::-1]

This uses extended slices with a negative step to walk backwards through sand get the reverse.

这使用带有负步的扩展切片向后走s并获得相反的结果。

回答by Aly

baab = palindrome and has length of 4 which is even

baab = 回文,长度为 4,是偶数

回答by PaulMcG

Try this:

试试这个:

is_palindrome = lambda s : all(s1==s2 for s1,s2 in zip(s[:len(s)/2],s[-1:-(len(s)+1)/2:-1]))

only checks the front half with the back half, and short-circuits as soon as a mismatch is found.

只检查前半部分和后半部分,一旦发现不匹配就短路。

回答by Andrew Noyes

Simple case: aa.

简单案例:aa。

More complicated case: aaaa.

更复杂的情况:aaaa。

And so on.

等等。

回答by Attila O.

Even length strings can be palindromes too. Wikipediadoesn't say anything about this restriction.

甚至长度字符串也可以是回文。维基百科没有说明这个限制。

回答by Mohamed Yahya

If string.length is even Then : All chars count should be even, so we can not have a char with odd count.

如果 string.length 是偶数那么:所有字符数都应该是偶数,所以我们不能有一个奇数的字符。

If string.length is odd Then: One char count must be odd, so not all chars' count should be even.

如果 string.length 是奇数 那么:一个字符的计数必须是奇数,因此并非所有字符的计数都应该是偶数。

--------------- I implemented the following JavaScript for the follow up roles :

--------------- 我为后续角色实现了以下 JavaScript:

function isStrPermutationOfPalindrome(_str) { // backward = forward
    var isPermutationOfPalindrome = true;
    var _strArr = [..._str];
    var _strArrLength = _strArr.length;
    var counterTable = getCharsTabularFrequencies(_str);
    var countOdd = 0;
    var countEven = 0;
    for (let [ky, val] of counterTable) {
        if (val % 2 == 0) {
            countEven = countEven + 1;
        } else {
            countOdd = countOdd + 1;
        }
    }
    if (_strArrLength % 2 == 0) {
        //Even count of all characters,otherwise false.
        //so can not have a character with odd count.
        if (countOdd != 0) {
            isPermutationOfPalindrome = false;
        }

    } else {
        //Odd count of 1 character
        //so not all chars with even count, only one char of odd count.

        if (countOdd > 1 || countOdd == 0) { //no odd, or more than one odd [ only one odd should be to return true]
            isPermutationOfPalindrome = false;
        }
    }
    return isPermutationOfPalindrome;
}


function getCharsTabularFrequencies(str) {
    str = str.toLowerCase();
    var arr = Object.assign([], str);
    var oMap = new Map();
    var _charCount = 0;
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] === ' ') {
            continue;
        }
        _charCount = 0;
        for (let j = 1; j < arr.length; j++) {
            {
                if (arr[i] === arr[j]) {
                    _charCount = _charCount + 1;
                }
            }
        }
        if (i == 0)
            _charCount = _charCount + 1;
        if (!oMap.has(arr[i]))
            oMap.set(arr[i], _charCount)
    }
    return oMap;
}

let _str = 'tactcoapapa';
console.log("Is a string of '" + _str + "' is a permutation of a palindrome ? ANSWER => " + isStrPermutationOfPalindrome(_str));

回答by RAHIMAN

n=raw_input("Enter a string==>")
n=int(n)

start=0
term=n

while n>0:
    result=n%10
    start=start*10+result
    n=n/10

print start

if term==start:
    print "True"
else:
    print "False"