5
\$\begingroup\$

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)]
\$\endgroup\$
4
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ I would let the caller deal with the exception instead of catching it silently and potentially hiding bugs. Exceptions are there for a reason! \$\endgroup\$ – Solomon Ucko Feb 24 '18 at 14:22
2
\$\begingroup\$

To avoid iterating the input list two times, you should just use a normal for loop and two counters:

def manipulate_data(data):
    positive_count = 0
    negative_sum = 0
    for n in data:
        if n > 0:
            positive_count += 1
        elif n < 0:
            negative_sum += n

    return [positive_count, negative_sum]

This also has the side effect that it’s super easy to read, so you understand the logic very quickly.

Also, such a function should not just silently return None on failure. If there is an issue with the input, that issue should pop up as an exception. Here, we can just leave that to Python itself: If data is not iterable, an exception will be raised; if an element in data is not comparable to a number, another exception is raised. When the function completes successfully, you can be sure that there is valid output.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.