Feedback on the implementation of a function that compares integer characters in Python

I made a small function, which, given the tuple, compares if all the elements in this tuple have the same sign.

For example, tuple = [-1, -4, -6, -8]good, but [-1, -4, 12, -8]bad. I'm not sure I made the smartest implementation, so I know this is the place to ask about.

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
+3
source share
9 answers

This may help you:

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

You can change <and> to <= and> = depending on how you want to handle 0.

+14
source

Following @EOL's solution, but works without indexing the list or repeating it several 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)

, / :

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

( 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 .

Mark Byers , .

+1

nit, :

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

all , , , , , :

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

... python.

+1

, , ?

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 sum
map(abs, a) = [1, 4, 8]
sum(map(abs, a)) = 13   # the tuple sum of each element absolute value

13, .

2:

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

(11 13), .

+1

, ..

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.

gorups 0 . >=,

+1
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
+1

, . , :

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, then zero would be considered a neutral sign. I'm not sure if this is a better implementation than current answers, but it can be faster for large datasets.

0
source

Using a principal that multiplies your numbers gives a positive result, if they are all the same, others are 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

It does not handle zeros, though ...

0
source

Source: https://habr.com/ru/post/1782680/


All Articles