Arush Singh
Arush Singh

Reputation: 31

How do we get a function that returns a list in Python?

So I'm new to Python and heres my code:

def sum_is_less_than(numeric_value, list_of_numbers):
    total = 0
    for number in list_of_numbers:
        total = total + number
        if total > numeric_value:
            break
        print(total)

numeric_value = 100
list_of_numbers = [2, 3, 45, 33, 20, 14, 5]

sum_is_less_than(numeric_value, list_of_numbers)

So what this code is doing, it's adding the values of the list as long as it's under the given numeric value. I want the code to output the first N elements in the list whose sum is less than the given numeric value.

For example: [1,2,3,4,5,6] and given numeric value is 10

I want the code to output [1,2,3] as adding 4 would make the sum greater or equal to the given numerical value.

Upvotes: 0

Views: 1334

Answers (3)

psnx
psnx

Reputation: 668

I would do it this way (short, efficient and pythonic). The first expression is a generator, meaning that it does not calculate values unnecessarily.

def sum_is_less_then(numeric_value, list_of_numbers: list):
    res = (sum(list_of_numbers[:idx]) for idx, _ in enumerate(list_of_numbers))
    return [x for x in res if x < numeric_value]

print (sum_is_less_then(30, [1,2,4,5,6,7,8,3,3,6]))
# result: [0, 1, 3, 7, 12, 18, 25]

Upvotes: 1

Zeitproblem
Zeitproblem

Reputation: 175

So, if you want to get a list out of your function you need to actually return something. Here, output starts as an empty list and gets appended with values from yout original list list_of_numbers, until the sum is higher then the passed numeric value.

def sum_is_less_than(numeric_value, list_of_numbers):
        total = 0
        output = []
        for number in list_of_numbers:
            total = total + number
            output.append(number) 
            if total > numeric_value:
                return output
        return output

A use case would be:

value = 10
list_of_numbers = [3,4,5,6]
list_sum_smaller_then_value = sum_is_less_than(numeric_value, list_of_numbers)

Upvotes: 1

Anton Kononenko
Anton Kononenko

Reputation: 31

def sum_is_less_than(numeric_value, list_of_numbers):
    total = 0
    for number in list_of_numbers:
        total += number
        if total < numeric_value:
            print(number)
        else:
            break

numeric_value = 10
list_of_numbers = [1,2,3,4,5,6]

sum_is_less_than(numeric_value, list_of_numbers)

Upvotes: 1

Related Questions