Home > Back-end >  How do we get a function that returns a list in Python?
How do we get a function that returns a list in Python?

Time:05-11

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.

CodePudding user response:

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)

CodePudding user response:

First, don't post the question with no information.

def sum_is_less_than(numeric_value, list_of_numbers):
    sum_l = 0
    l = []
    i = 0
    while numeric_value>sum_l:
        if i > len(list_of_numbers)-1:
            break
        sum_l =list_of_numbers[i]
        l.append(list_of_numbers[i])
        i =1
    return l

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

print(sum_is_less_than(numeric_value,list_of_numbers))

CodePudding user response:

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
  • Related