2014-02-17 41 views
10

我試圖做一個程序,檢查一個單詞是否是一個迴文,我已經得到了迄今爲​​止,它與單詞有偶數量的數字。如果字母數量很奇怪,我知道如何讓它做些什麼,但我不知道如何找出一個數字是否奇怪。有沒有簡單的方法來查找一個數字是奇數還是偶數?檢查一個數字是奇數還是蟒蛇

僅供參考,這是我的代碼:

a = 0 

while a == 0: 
    print("\n \n" * 100) 
    print("Please enter a word to check if it is a palindrome: ") 
    word = input("?: ") 

    wordLength = int(len(word)) 
    finalWordLength = int(wordLength/2) 
    firstHalf = word[:finalWordLength] 
    secondHalf = word[finalWordLength + 1:] 
    secondHalf = secondHalf[::-1] 
    print(firstHalf) 
    print(secondHalf) 

    if firstHalf == secondHalf: 
     print("This is a palindrom") 
    else: 
     print("This is not a palindrom") 


    print("Press enter to restart") 
    input() 

感謝

+1

我不知道該怎麼你會在Python表達這一點,但(字長模2)== 1如果將一個單詞有字符數爲奇數的是真實的。 – 2014-02-17 19:05:52

回答

56
if num % 2 == 0: 
    pass # Even 
else: 
    pass # Odd 

%標誌就像是劃分僅是檢查剩餘的,所以如果2除以數量有一個的0其餘它甚至否則奇怪。

+11

Python條件不需要括號 – lejlot

0

其中一個最簡單的方法是使用德模運算%。如果n%2 == 0,那麼你的號碼是偶數。

希望它能幫助,

0

奇數長度單詞的中間字母在確定單詞是否是迴文時是無關緊要的。只要忽略它。

提示:你需要的是一個輕微的調整到以下行來完成這項工作的所有字長度:

secondHalf = word[finalWordLength + 1:] 

附:如果你堅持分開處理這兩種情況,if len(word) % 2: ...會告訴你,單詞有奇數個字符。

def is_palindrome(word): 
    if word == word[::-1]: 
     return True 
    else: 
     return False 
6

如果這個詞有偶數或奇數數量FO信它不應該的問題

if wordLength % 2 == 0: 
    print "wordLength is even" 
else: 
    print "wordLength is odd" 

對於您的問題,最簡單的就是檢查這個詞是否與其顛倒的兄弟相同。你可以做到這一點與word[::-1],其採取的每一個字符從年底開始創建word名單:

def is_palindrome(word): 
    return word == word[::-1] 
+5

爲什麼不只是'return word == word [:: - 1]'?如果條件爲真,則返回True,如果條件爲假,則返回False,與返回條件相同... – Hyperboreus

+2

@Hyperboreus只是希望儘可能明確,因爲我覺得OP對Python來說很新穎。 – IanAuld

+0

這一款在簡單和清晰度上勝過我自己的kludgy解決方案! –

24

同樣爲其他語言,最快的「模2」(奇/偶)操作完成使用bitwise and操作:

if x & 1: 
    return 'odd' 
else: 
    return 'even' 
+9

「明確比隱含更好;; 簡單比複雜更好。」,來自Python的禪 –

相關問題