“或"是什么意思?在python return语句中执行/列表子集总和的说明 [英] What does "or" do in a python return statement / Explanation of list subset sum

查看:142
本文介绍了“或"是什么意思?在python return语句中执行/列表子集总和的说明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在挑战coderbyte的Python Array Addition,但我做得不太正确.我看到了另一个用户的正确代码,对此我感到有些困惑.主要是,return语句中的或"是做什么的?这使我无法完全理解该问题的解决方案.谢谢.

I was doing coderbyte's Python Array Addition I challenge, but I couldn't get it quite right. I saw another user's correct code, and I'm kind of puzzled by it. Mainly, what does "or" do in a return statement? It's preventing me from fully understanding the solution to this problem. Thanks.

问题如下: 如果可以将数组中数字的任意组合加起来等于数组中的最大数字,则让函数ArrayAdditionI(arr)接受存储在arr中的数字数组并返回字符串true,否则返回字符串false.例如:如果arr包含[4,6,23,10,1,3],则输出应返回true,因为4 + 6 + 10 + 3 =23.该数组将不会为空,不会包含所有相同的元素,并可能包含负数.

The question is as follows: Have the function ArrayAdditionI(arr) take the array of numbers stored in arr and return the string true if any combination of numbers in the array can be added up to equal the largest number in the array, otherwise return the string false. For example: if arr contains [4, 6, 23, 10, 1, 3] the output should return true because 4 + 6 + 10 + 3 = 23. The array will not be empty, will not contain all the same elements, and may contain negative numbers.

def subsetsum(target, arr):
    if len(arr) == 0:
        return target == 0

    return subsetsum(target, arr[1:]) or subsetsum(target - arr[0], arr[1:])

def ArrayAdditionI(arr): 
    arr = sorted(arr)
    target = arr[-1]
    arr = arr[:-1]
    return 'true' if subsetsum(target, arr) else 'false'


# keep this function call here  
# to see how to enter arguments in Python scroll down
print ArrayAdditionI(raw_input())           

推荐答案

以下是解决此问题的方法:

Here's how to break this down:

return subsetsum(target, arr[1:]) or subsetsum(target - arr[0], arr[1:])

其格式为return a or b,其中a = subsetsum(target, arr[1:])b = subsetsum(target - arr[0], arr[1:]).

如果bool(a)是True,则表达式a or b短路并返回a的值. 如果bool(a)False,则必须对b求值以确定表达式a or b的值.

If bool(a) is True, then the expression a or b short circuits and returns whatever the value of a is. If bool(a) is False, then b must be evaluated to determine the value of the expression a or b.

因此,return a or b是以下各项的简写,由于短路逻辑,如果bool(a)为True,则不会评估b(如果它是一个函数).

Thus, return a or b is shorthand for the following, with the benefit that b is not evaluated (if it's a function) if bool(a) is True, thanks to short-circuiting logic.

if bool(a):
    return a
else:
    return b

这篇关于“或"是什么意思?在python return语句中执行/列表子集总和的说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆