簡體   English   中英

遞歸函數調用和/或循環重復不如預期

[英]recursive function call and/or loop repeats not as expected

此函數應為操作列表和相應的選項列表生成是或否的用戶輸入問題。 它返回一個布爾值列表。 例如['watch','play',...]和['footbal','sports',...] =>你看足球嗎? _等

問題:

當用戶輸入錯誤時,該函數會經常迭代 - 盡管這些是您可以看到的單獨處理的!

我確定使用單個元素列表這個代碼工作正常。 所以我的代碼。 我知道打印調試,我是一個血腥的初學者。

def yes_or_no(action, choices, *argv):
    decisions = []
    #remember previous decisions (in case an error occured)
    for arg in argv:
        decisions = arg
    print('choices: ', choices)
    print('decisions: ', decisions)
    for choice in choices:
        print(choice)
        decision = input('Do you want to {} {}? Plase, type [y/n]: '.format(action, choice))
        try:
            decision = str(decision)
            if decision == 'y':
                decisions.append(True)
                pass
            elif decision == 'n':
                decisions.append(False)
                pass
            else:
                print('\nYour input was neither y = \'yes\' nor n = \'no\'.\nOnce again.')
                new_choices = choices[choices.index(choice):]
                yes_or_no(action, new_choices, decisions)
        except ValueError:
            print('\nYour input was neither y = \'yes\' nor n = \'no\'.\nOnce again.')
            new_choices = choices[choices.index(choice):]               
            yes_or_no(action, new_choices, decisions)
    print(decisions)
    return (decisions)

好吧,當我第一次輸入無效輸入時,遞歸開始,但選擇中的選擇迭代2(!)次,盡管此列表中只有一個元素!

因此我將pr​​int()語句添加到代碼中以查看 - 這很瘋狂!

以下是命令行的結果:

choices:  ['football', 'sports']
decisions:  []
watch
Do you want to watch football? Plase, type [y/n]: sure

Your input was neither y = 'yes' nor n = 'no'.
Once again.
choices:  ['football', 'sports']
decisions:  []
football
Do you want to watch football? Plase, type [y/n]: n
sports
Do you want to watch sports? Plase, type [y/n]: y
sports
Do you want to watch sports? Plase, type [y/n]: y
[False, True, True]

這是因為你一直通過迭代choices當你給錯誤decision的最后一個元素之前choices 這里的解決方案應該是在調用函數后添加return語句。 您使用該語句更新的代碼段將如下所示:

def yes_or_no(action, choices, *argv):
    decisions = []
    #remember previous decisions (in case an error occured)
    for arg in argv:
        decisions = arg
    print('choices: ', choices)
    print('decisions: ', decisions)
    for choice in choices:
        print(choice)
        decision = input('Do you want to {} {}? Plase, type [y/n]: '.format(action, choice))
        try:
            decision = str(decision)
            if decision == 'y':
                decisions.append(True)
                pass
            elif decision == 'n':
                decisions.append(False)
                pass
            else:
                print('\nYour input was neither y = \'yes\' nor n = \'no\'.\nOnce again.')
                new_choices = choices[choices.index(choice):]
                return yes_or_no(action, new_choices, decisions)
        except ValueError:
            print('\nYour input was neither y = \'yes\' nor n = \'no\'.\nOnce again.')
            new_choices = choices[choices.index(choice):]               
            return yes_or_no(action, new_choices, decisions)
    print(decisions)
    return (decisions)

您好,我是我 - 我只能用假郵件重新登錄我快速創建的帳戶:P

我在幾分鍾內得到了一個有用的答案,因此我只是想分享我的最終解決方案,這個遞歸處理“是或否” - 由移交給函數的兩個列表生成的問題。

def yes_or_no(action, choices, *argv):

    error_message = '\nYour input was neither y = \'yes\' nor n = \'no\'.\nOnce again.\n'
    decisions = []

    #remember previous decisions (in case an error occured)
    for arg in argv:
        decisions = arg

    for choice in choices:
        decision = input('Do you want to {} {}? Plase, type [y/n]: '.format(action, choice))

        try:
            decision = str(decision)
            if decision == 'y':
                decisions.append(True)
            elif decision == 'n':
                decisions.append(False)
            else:
                print(error_message)
                decisions = yes_or_no(action, choices[choices.index(choice):], decisions)
                break
        except ValueError:
            print(error_message)
            decisions = yes_or_no(action, choices[choices.index(choice):], decisions)
            break

    return (decisions)

簡歷:對於動機問題(“是或否 - 問題處理”)的這種解決方案可能不是最有效的問題 - 但它是全面的並且很容易應用於任何此類問題。 你可能已經認識到我沒有使用建議的'return',因為'break'會產生相同的效果,因為只有一個(!)循環遞歸('選擇中的選擇:')要打破。 我更喜歡'break'而不是'return',因為我認為它在技術上更快地被編譯器解決了。

缺點:到目前為止我只想到了一個缺點。 在許多無效輸入的情況下 - 我的意思是數百萬或更多 - 這種遞歸將需要越來越多的存儲空間。 但我想,這對於遞歸來說是眾所周知的。 ;-)

暫無
暫無

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

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