简体   繁体   English

Python 减少 Boolean 行为不符合预期

[英]Python Reduce With Boolean Not Behaving As Expected

Can someone explain why this won't determine whether an array is monotonic?有人可以解释为什么这不能确定数组是否是单调的吗? Not sure I understand reduce() completely.不确定我是否完全理解 reduce()。 I have used it for aggregating sums, but figured it should be able to aggregate a boolean here, right?我用它来汇总总和,但认为它应该能够在这里汇总 boolean,对吧?

from functools import reduce
def isMonotonic(array):
    # Write your code here.
    if not array or len(array) == 1:
        return True
    return reduce(lambda x, y: bool(x <= y), array, True) or reduce(lambda x, y: bool(x >= y), array, True)

From functools doc: functools.reduce(function, iterable[, initializer]) Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value.来自functools doc:functools.reduce(function, iterable[, initializer]) 将两个arguments的function从左到右累加到iterable的item上,从而将iterable缩减为单个值。 For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5).例如,reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) 计算 ((((1+2)+3)+4)+5)。 The left argument, x, is the accumulated value and the right argument, y, is the update value from the iterable.左边的参数 x 是累积值,右边的参数 y 是迭代的更新值。 If the optional initializer is present, it is placed before the items of the iterable in the calculation, and serves as a default when the iterable is empty.如果存在可选初始化器,则在计算中将其放置在可迭代项之前,并在可迭代项为空时用作默认值。 If initializer is not given and iterable contains only one item, the first item is returned.如果没有给出初始化程序并且可迭代只包含一个项目,则返回第一个项目。

Thus you get result of the comparison of all of the values before and the last one.因此,您将获得之前和最后一个值的所有值的比较结果。 Because of duck typing the comparison between an int and a bool is possible.由于鸭子类型,int 和 bool 之间的比较是可能的。 False is 0, True is 1.Just try假为0,真为1。试一试

print(True >= 2)

In strictly typed languages, this would cause an error.在严格类型的语言中,这会导致错误。

What I would do:我会做什么:

def isMonotonic(a):
    # Write your code here.
    if not a or len(a) == 1:
        return True
    # create an list of tuples of the pairs, the last value in the second list is ignored because of the laziness of zip. Use a list so it can be used multiple times.
    a = list(zip(a[1:],a))
# create a list of comparison results. Then check if all comparisons are true.
return all(x <= y for x,y in a) or all(x >= y for x,y in a)

print(isMonotonic([1,2,3,4,5]))
print(isMonotonic([1,2,3,7,5]))
print(isMonotonic([5,3,2,1]))
print(isMonotonic([5,3,3,4,1]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM