簡體   English   中英

如何在Python中檢查回文?

[英]How to do check for a palindrome in Python?

嗨,我正在為三個數字的整數處理python函數isPalindrome(x) ,如果百位數等於一個數字,則返回True,否則返回false。 我知道我必須在這里使用字符串,這就是我所擁有的:

def isPal(x):
    if str(1) == str(3):
        return "True"

    else:
        return "False"

str(0)是單位位置, str(2)是百位位置。 我得到的只是假的? 謝謝!

數組訪問使用[]而不是() 同樣,如果您要查找數百個單位,請記住數組的索引為0,這是代碼的簡化版本。

def is_pal(num):
    return num[0] == num[2]

>>> is_pal('123')
False
>>> is_pal('323')
True

您可能需要將數字作為參數,然后將其轉換為字符串:

def is_pal(num):
    x = str(num)
    return x[0] == x[2]

請注意,您只需要檢查一下字符串是否等於它的反向值即可,該方法適用於任意數量的數字:

>>> x = '12321'
>>> x == x[::-1]
True

str(1)將創建一個整數值1的字符串。該字符串將不等於整數值3的字符串值-因此它始終為False。

您應該返回TrueFalse ,而不是字符串“ True”和“ False” ...

這就是您要考慮的上述因素...(適用於任何長度)

def pal(num):
    forward = str(num)
    backward = ''.join(reversed(forward))
    return forward == backward

您的問題是str(1) == '1'str(3) == '3' 您還將返回讀取'True''False'字符串值,而不是使用實際的TrueFalse值。

讓我為您提出一個簡單得多的功能:

def isPal(x):
    s = str(x)          # convert int to str
    return s == s[::-1] # return True if s is equal to its reverse

s[::-1]創建字符串的反向字符; 例如'foo'[::-1] == 'oof' 這是因為擴展的切片符號而起作用。

str()將值轉換為str 您要訪問每個字符。 您可能想對一些不同的技術進行基准測試。

>>> t1 = timeit.Timer(stmt="""\
... def isPal(x):
...     return x//100 == x%10
... isPal(434)
... isPal(438)
... """)
>>> t2 = timeit.Timer(stmt="""\
... def isPal(x):
...     return str(x)[0] == str(x)[2]
... isPal(434)
... isPal(438)
... """)
>>> print "%.2f usec/pass" % (1000000 * t1.timeit(number=100000)/100000)
0.97 usec/pass
>>> print "%.2f usec/pass" % (1000000 * t2.timeit(number=100000)/100000)
2.04 usec/pass

因此,看起來mod技術有效:

def isPal(x):
    return x//100 == x%10

不知道為什么人們在除法和取模時會堅持使用字符串的想法:

def isPal(x):
    return (x/100)%10 == x%10

如果該數字不大於999(如OP所述為3位數字),則簡化為

def isPal(x):
    return x/100 == x%10

str(x)傳遞傳遞給它的任何值的字符串值,因此在您的情況下為字符串"1"或字符串"3" 但是,您真正想要的是訪問給定數字的第一位和第三位。 因此,首先要將該數字轉換為字符串(例如,使用str(num)),然后必須考慮字符串中的索引以0開頭,而不是以1開頭。因此,工作代碼可能如下所示:

def isPal(x):
  if str(x)[0] == str(x)[2]:
    return 'true'
  else:
    return 'false'

輸出:

> isPal(101)
true
> isPal (203)
false

str(1)只是為您提供數字1的字符串表示形式:

>>> x = 357
>>> str(1)
'1'

您想要的是x的字符串表示形式的第一個索引

>>> x = 357
>>> str(x)    #string representation of x
'357'
>>> str(x)[0] #first index of that
'3'
>>> str(x)[2] #third index of that
'7'
>>> str(x)[0]==str(x)[2] #compare 1st and last
False
>>> x = 525
>>> str(x)[0]==str(x)[2] #compare 1st and last
True

您比較數字1和3,但不必比較輸入變量的索引。

x = 1000
def isPal(x):
    return str(x[-1]) == str(x[-3]):

看來您仍然需要學習Python語法

這是一種實現您所需的方法:

>>> def isPal(x):
...     x_as_str = str(x)
...     if len(x_as_str) != 3:
...         raise Exception("{} is not of length 3".format(x))
...     return x_as_str[0] == x_as_str[2]
...
>>> isPal(42)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "<input>", line 4, in isPal
Exception: 42 is not of length 3
>>> isPal(420)
False
>>> isPal(424)
True

一個較小的解決方案是:

def isPalindrome(x):    
    return str(x) == str(x)[::-1]

這將適用於單詞和整數值。

def is_palindrome() :
a=(raw_input("enter the name : "))
b=a[::-1]
    if b == a:
    print " it is palindarome"
    else:
    print "  it is not palindarome"

is_palindrome()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM