关于Python中比较整数符号的函数实现的反馈

发布于 2024-10-09 23:54:35 字数 609 浏览 3 评论 0原文

我创建了一个小函数,给定一个元组,比较该元组中的所有元素是否具有相同的符号。

例如,tuple = [-1, -4, -6, -8] 是好的,而 [-1, -4, 12, -8] 是坏的。我不确定我是否已经做出了最明智的实施,所以我知道这是提问的地方。

def check_consistent_categories(queryset):
    try:
        first_item = queryset[0].amount

        if first_item < 0:
            for item in queryset:
                if item > 0:
                    return False
            return True
        else:
            for item in queryset:
                if item < 0:
                    return False
            return True
    except:
        return False

I've made a small function which, given a tuple, compares if all elements in this tuple is of the same sign.

E.g., tuple = [-1, -4, -6, -8] is good, while [-1, -4, 12, -8] is bad. I am not sure I've made the smartest implementation, so I know this is the place to ask.

def check_consistent_categories(queryset):
    try:
        first_item = queryset[0].amount

        if first_item < 0:
            for item in queryset:
                if item > 0:
                    return False
            return True
        else:
            for item in queryset:
                if item < 0:
                    return False
            return True
    except:
        return False

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

自此以后,行同陌路 2024-10-16 23:54:35

这可能对您有帮助:

def all_same_sign(ints):
    return all(x < 0 for x in ints) or all(x > 0 for x in ints)

您可能想要更改<和>到 <= 和 >= 取决于您想要如何处理 0。

This might help you:

def all_same_sign(ints):
    return all(x < 0 for x in ints) or all(x > 0 for x in ints)

You may want to change < and > to <= and >= depending on how you want to treat 0.

是伱的 2024-10-16 23:54:35

在 @EOL 的解决方案之后,但无需列表索引或多次迭代即可工作。

def all_same_sign(sequence):
    items = iter(sequence)
    try:
        first = items.next() > 0
    except StopIteration:
        return True
    return all((item > 0) == first for item in items)

我也想到了这一点,但没有利用所有/任何短路:

def all_same_sign(sequence):
    return len(set(item > 0 for item in sequence)) <= 1

After @EOL's solution, but works without list indexing or iterating multiple times.

def all_same_sign(sequence):
    items = iter(sequence)
    try:
        first = items.next() > 0
    except StopIteration:
        return True
    return all((item > 0) == first for item in items)

This also occurred to me, but doesn't take advantage of all/any short-circuiting:

def all_same_sign(sequence):
    return len(set(item > 0 for item in sequence)) <= 1
神魇的王 2024-10-16 23:54:35

只是一个不相关的问题,因为您正在这样做:

try:
    [...]
except:
    [...]

您忽略了所有异常,请非常小心,我的朋友,这将隐藏很多错误,而不是在进行异常处理时始终保持精确,例如:

try:
    [...]
except IndexError:
    # Handle out of index
except IOError:
    # Handle I/O error

等等。在编写更大的 Python 应用程序时请记住这一点。

Just one unrelated nit, since you are doing this:

try:
    [...]
except:
    [...]

You are ignoring all of the exceptions, be very careful my friend, this will be hiding lots of bugs, instead always be precise while doing exception handling e.g:

try:
    [...]
except IndexError:
    # Handle out of index
except IOError:
    # Handle I/O error

etc. Keep this in mind while coding a larger python application.

云雾 2024-10-16 23:54:35

这是一种很好的 Python 方法(使用 all()):(

from math import copysign

sign = lambda x: copysign(1, x)  # Sign function

def check_consistent_categories(sequence):
    main_sign = sign(sequence[0])
    return all(sign(y) == main_sign for y in sequence)

对于 Python 2.6+,它引入了 math.copysign() 函数)。该解认为 0 为正。

不过,马克·拜尔斯的解决方案更加灵活,而且也可以说更加清晰。

Here is a nice pythonic way of doing this (using all()):

from math import copysign

sign = lambda x: copysign(1, x)  # Sign function

def check_consistent_categories(sequence):
    main_sign = sign(sequence[0])
    return all(sign(y) == main_sign for y in sequence)

(for Python 2.6+, which introduced the math.copysign() function). This solution considers that 0 is positive.

Mark Byers' solution is more flexible, though, and it is also arguably more legible.

情栀口红 2024-10-16 23:54:35

为什么不利用这样一个事实:如果所有数字的符号相同,那么每个单独数字的绝对值之和将等于每个数字之和的绝对值?

def check_sign(queryset):
    return abs(sum(queryset)) == sum(map(abs, queryset))

显示数学细节的示例

情况 1: 所有数字都具有相同的符号

a = (-1, -4, -8)
sum(a) = -13
abs(sum(a)) = 13        # the absolute value of the tuple's sum
map(abs, a) = [1, 4, 8]
sum(map(abs, a)) = 13   # the tuple's sum of each element's absolute value

两种方法的结果都是 13,因此符号相同。

情况 2: 并非所有数字都具有相同的符号

b = (-1, 4, 8)
sum(b) = 11
abs(sum(b)) = 11        # the absolute value of the tuple's sum 
map(abs, b) = [1, 4, 8]
sum(map(abs, b)) = 13   # the tuple's sum of each element's absolute value

这些方法会生成不同的数字(11 和 13),因此符号并不全部相同。

Why not take advantage of the fact that if all numbers are the same sign, then the sum of the absolute value of each individual number will be equal to the absolute value of the sum of each number?

def check_sign(queryset):
    return abs(sum(queryset)) == sum(map(abs, queryset))

Example Showing Details of the Math

Case 1: All numbers have the same sign

a = (-1, -4, -8)
sum(a) = -13
abs(sum(a)) = 13        # the absolute value of the tuple's sum
map(abs, a) = [1, 4, 8]
sum(map(abs, a)) = 13   # the tuple's sum of each element's absolute value

Both methods yield 13, so the signs are the same.

Case 2: Not all numbers have the same sign

b = (-1, 4, 8)
sum(b) = 11
abs(sum(b)) = 11        # the absolute value of the tuple's sum 
map(abs, b) = [1, 4, 8]
sum(map(abs, b)) = 13   # the tuple's sum of each element's absolute value

The methods yield different numbers (11 and 13), so the signs are not all the same.

悲欢浪云 2024-10-16 23:54:35

这是一个也可以与生成器等一起正常工作的方法。

def all_same_sign(ints):
    ints = iter(ints)
    first_is_positive = next(ints) > 0
    return all( (x>0) == first_is_positive for x in ints)

如果 ints 为空,则会出现 StopIteration 异常。

此版本将 0 与负数组合在一起。如果您希望与正数分组,请使用 >=

Here is one that works fine with generators etc. too

def all_same_sign(ints):
    ints = iter(ints)
    first_is_positive = next(ints) > 0
    return all( (x>0) == first_is_positive for x in ints)

If ints is empty, you get a StopIteration exception.

This version gorups 0 with the negative numbers. Use >= if you wish to group with the positive numbers instead

樱&纷飞 2024-10-16 23:54:35
def all_same_sign(iterable):
    # Works with any iterable producing any items that can be compared to zero.
    # Iterates through the input no more than once, and this fact is immediately
    # obvious from the code.
    # Exits as soon as a bad combination has been detected.
    pos = neg = zero = False
    for item in iterable:
        if item > 0:
            pos = True
        elif item < 0:
            neg = True
        else:
            zero = True
        # Adjust the following statement if a different
        # treatment of zero is required.
        # Redundant parentheses added for clarity.
        if (pos and neg) or zero:
            return False
    return True
def all_same_sign(iterable):
    # Works with any iterable producing any items that can be compared to zero.
    # Iterates through the input no more than once, and this fact is immediately
    # obvious from the code.
    # Exits as soon as a bad combination has been detected.
    pos = neg = zero = False
    for item in iterable:
        if item > 0:
            pos = True
        elif item < 0:
            neg = True
        else:
            zero = True
        # Adjust the following statement if a different
        # treatment of zero is required.
        # Redundant parentheses added for clarity.
        if (pos and neg) or zero:
            return False
    return True
人事已非 2024-10-16 23:54:35

如果您的数字已排序,您只需比较两端即可。如果不是,您可以对它们进行排序:

def same_sign(numbers):
    numbers = sorted(numbers)
    #if numbers[0]==0: return True                Uncomment if you consider 0 positive
    if numbers[0]*numbers[-1]>0: return True
    return False

如果您将其更改为 >=0 零将被视为符号中性。我不确定这是否是比当前答案更好的实现,但对于大量数据来说它可能会更快。

If your numbers are sorted you only need to compare the ends. If not you could sort them:

def same_sign(numbers):
    numbers = sorted(numbers)
    #if numbers[0]==0: return True                Uncomment if you consider 0 positive
    if numbers[0]*numbers[-1]>0: return True
    return False

If you changed this to >=0 zero would be considered sign neutral. I'm not sure if this is a better implementation than the current answers, but it could be faster for large sets of data.

待天淡蓝洁白时 2024-10-16 23:54:35

使用这样的原理:如果数字相同,则相乘得出正结果,否则得出负结果,

import operator

def all_same_sign(intlist):
    return reduce(operator.mul, intlist) > 0

>>> all_same_sign([-1, -4, -6, -8])
True
>>> all_same_sign([-1, -4, 12, -8])
False

但这不能处理零......

Using the principal that multiplying your numbers gives a positive result if they all the same, else negative,

import operator

def all_same_sign(intlist):
    return reduce(operator.mul, intlist) > 0

>>> all_same_sign([-1, -4, -6, -8])
True
>>> all_same_sign([-1, -4, 12, -8])
False

This doesn't handle zeros though...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文