簡體   English   中英

遞歸程序:我在做什么錯?

[英]Recursive Program: What am I doing wrong?

我正在嘗試編寫代碼來分析單詞是否是回文。 順便說一句,回文是向后和向前閱讀相同的單詞。 例如“女士”或“中午”

嘗試一下:

x = raw_input("please enter a word:\n")
L = len(x)

 # this part returns the first letter of the word

def first(word):
    return word[0]

# this part returns the last letter of the word

def last(word):
    return word[-1]


def middle(word):
    return word[1:-1]


def is_palindrome(word):
    if L <= 2:
        print 'enter a word with at least three letters'
    elif first(word) != last(word):
        print 'This word is not a palindrome'
    else:
        word = middle(word)
        is_palindrome(word)

is_palindrome(x) 

但是當執行時,我得到

IndexError: string index out of range
...line 7, in first return word[0]

“ is_palindrome”的第一個分支工作正常。 即,當單詞不是回文時,我不會出錯。 像“ noopn”一樣執行沒有錯誤,但是錯誤在第二個分支中

我已經玩了很多次此代碼,但無法弄清楚“迭代部分”,我已經找到了答案,但是我不想看它。 我需要弄清楚兩件事:1.一種使is_palindrome函數中的迭代正確運行的方法嗎? 2.最終退出程序的方法。

你們能否在不提供解決方案的情況下指導我如何回答這些問題?

最后我應該在哪里寫上打印說明:print'這個詞是回文'

謝謝

為了實現您的目標,為什么不僅僅使用:

string[::-1] == string

您回答的原因是只有1個字母時, middle將返回一個空字符串,然后''[0]將導致錯誤。

您需要一個基本案例進行遞歸。 一個字母的單詞是回文,而空字符串也是回文。

def is_palindrome(word):
    # handle the base case
    if len(word) <= 1:
        print 'This word is a palindrome'
    elif first(word) != last(word):
        print 'This word is not a palindrome'
    else:
        word = middle(word)
        is_palindrome(word)

如果要拒絕少於三個字母的單詞,則可以使用調用遞歸函數的幫助器函數:

def is_palindromeHelper(word):
    if len(word) <= 2:
        print 'enter a word with at least three letters'
    else:
        is_palindrome(word)

就個人而言,我更喜歡將支票和輸出分開。 因此is_palindrome()應該只返回答案,而不負責告訴用戶。 這使其更具可重用性。

def is_palindrome(word):
    # handle the base case
    if len(word) <= 1:
        return True
    elif first(word) != last(word):
        return False
    else:
        word = middle(word)
        return is_palindrome(word)

這使您能夠

x = raw_input("please enter a word:\n")
L = len(x)

if L <= 2:
    print 'enter a word with at least three letters'
elif is_plaindrome(word):
    print 'This word is a palindrome'
else:
    print 'This word is not a palindrome'

這將有效性檢查放在執行的最前面,而在遞歸中,只有在整個遞歸中有效的檢查。

(我懷疑,如果你的檢查是必要的話-是yoo ?沒有回文我們可以爭論空字符串,但是......)

接下來的改進步驟可能是忽略函數first()last()middle() -它們是微不足道的,並且僅使用一次,因此您可以在其中放置代碼。

在您的代碼中添加了一個額外的條件,它將解決您的問題。 如果只剩下一個字符,則無需調用is_palindrome()。

    x = raw_input("please enter a word:\n")
    L = len(x)

     # this part returns the first letter of the word

    def first(word):
        return word[0]


   # this part returns the last letter of the word

    def last(word):
        return word[-1]


    def middle(word):
        return word[1:-1]


    def is_palindrome(word):
        if L <= 2:
            print 'enter a word with at least three letters'
        elif first(word) != last(word):
            print 'This word is not a palindrome'
        else:
            word = middle(word)
            if len(word) > 1:
                is_palindrome(word)
            else:
                print 'This word is a palindrome'

    is_palindrome(x)

不建議使用大寫和空白的基本版本,我建議:

def is_palindrome(word):
    if len(word) < 3:
        print 'Enter a word with at least three letters'
    else:
        for letter in range(len(word)/2):
            if word[letter] != word[-letter - 1]:
                print "This word is not a palindrome"
                return
        print "This word is a palindrome"

雖然我認為它可能會親自刪除空白並使用.lower()進行比較。 然后它將是不區分大小寫的,並且還可以測試短語或句子。

好方向的家伙。 所有人都投票贊成。

這些指示使我可以編寫以下簡明代碼

代碼1

x = raw_input("enter a word to check if it is a palindrome:\n")

if x[::-1] == x:
    print 'yes this one is a palindrome'

else:
    print 'sorry try again by re-running the program'


代碼2

x = raw_input("enter a word to check if it is a palindrome:\n")

if len(x) <= 1:
    print 'Of course ', x, ' is a palindrome'

def is_palindrome(x):    
    if len(x) >= 2:
        if x[0]!=x[-1]:
            print 'This is not a palindrome'
        else:
            x = x[1:-1]
            return is_palindrome(x)
    print 'This is FINALLY a real palindrome'

is_palindrome(x)

我想我可以將is_palindrome函數作為條件語句len(x)<= 1的第二個分支包括在內,但是我更喜歡這種方式,因為代碼與該函數有關

暫無
暫無

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

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