HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Get count of positive numbers and sum of negative numbers

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
numbersgetsumandcountpositivenegative

Problem

Write a function called manipulate_data which will act as follows:


When given a list of integers, return a list, where the first element is the count of positives numbers and the second element is the sum of negative numbers.

Sample code

def manipulate_data(data):
    if isinstance(data, (list, tuple, set)):
        #didn't know where 0 stood so I excluded it
        return [len([n for n in data if isinstance(n, int) and n > 0]), sum(n for n in data if isinstance(n, int) and n < 0)]

Solution

The count of positive numbers can be better written as:

sum(n > 0 for n in data)


This will take a lot less memory (which is important if data becomes large), because it uses a generator expression.

Also, are all the checks of isinstance really needed? Is data sometimes not an iterable? And does it sometimes not contain integers? Because if not, then those checks will cost some time.

At the same time, it is usually better to ask for forgiveness than permission, so just use:

try:
    print len(data)
except AttributeError:  # will trigger if `data` has no `len` function
    pass


to be more inclusive and allow any custom iterable.

Code Snippets

sum(n > 0 for n in data)
try:
    print len(data)
except AttributeError:  # will trigger if `data` has no `len` function
    pass

Context

StackExchange Code Review Q#140920, answer score: 4

Revisions (0)

No revisions yet.