python函数中的return语句一定能得到执行,“或”是什么意思?在python 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.

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:])

This has the form return a or b where a = subsetsum(target, arr[1:]) and b = subsetsum(target - arr[0], arr[1:]).

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.

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值