簡體   English   中英

這個遞歸的python子集求和函數中發生了什么; 特別是在if / else塊中使用的or語句?

[英]What is going on in this recursive python subset sum function; specifically the or statement that is being used within an if/else block?

基本上,我的CS家庭作業的一部分是創建一個函數,該函數接受非負數L的參數列表,並返回這些數字的子集是否加起來等於給定的精確數量(另一個參數)。 我已經創建了該解決方案,但實際上是按照給我的“提示”說的,它涉及使用“或”語句,其中包含一個排除最后一個元素的遞歸函數和另一個包含該元素的遞歸函數。 我想出了這個:

def exact_change(target_amount, L):
    if len(L) == 0:
        return target_amount == 0
    else:
        print('target_amount is', target_amount, 'list is now', L)
        return exact_change(target_amount, L[1:]) or 
        exact_change(target_amount - L[0], L[1:])

它通過了所有的斷言測試,我嘗試通過添加打印語句來了解到底發生了什么。 這實際上使我更加困惑。

In [17]: exact_change(42, [25, 16, 2, 15])
target_amount is 42 list is now [25, 16, 2, 15]
target_amount is 42 list is now [16, 2, 15]
target_amount is 42 list is now [2, 15]
target_amount is 42 list is now [15]
target_amount is 40 list is now [15]
target_amount is 26 list is now [2, 15]
target_amount is 26 list is now [15]
target_amount is 24 list is now [15]
target_amount is 17 list is now [16, 2, 15]
target_amount is 17 list is now [2, 15]
target_amount is 17 list is now [15]
target_amount is 15 list is now [15]
Out[17]: True

讓我特別困惑的是,程序是如何選擇要使用的遞歸函數的-我感到困惑的另一件事是,列表在被切片時是如何擴展的。 也許我看錯了這些陳述? 任何幫助,將不勝感激!!

您正在使用大多數編程語言中都存在的邏輯OR語句的短路功能。 對於一般語句b1 OR b2 ,表達式b1首先被求值。 如果它的評估結果為true ,則整個語句的評估結果為true 如果不是,則對b2求值,整個語句求和為b2的結果。 並不是說如果b1評估為true ,則永遠不會評估b2 這通常在其他情況下使用。

將其應用到您的代碼中,您將獲得輸出中的函數調用。

暫無
暫無

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

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