Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use a while loop in python to add values in a list until they exceed a maximum value?

I am learning python V3 and have the following problem on a homework assignment:

In this exercise, your function will receive a list of numbers, and an integer. It will add the values in the list to a total as long as the total is less than or equal to the value of the second parameter. The sum of numbers in the list will always be larger than the second parameter's value.

I came up with the following solution:

def while11(nums,maxi):
    i=0
    total=0
    while total<=maxi:
        total+=nums[i]
    return total

The test parameters are as follows:

[1,1,1,1,1,1,1,1,1], 6
[2,2,2,2,2,2,2,2,2], 6
range(10, 1, -1), 25

The my function returns 7 and 8, respectively, for the first two sets of parameters. However, it should return 27 for the third set, but it returns 30. It appears to be adding 11,10, and 9 as opposed to 10,9, and 8.

like image 493
crhaag Avatar asked Dec 02 '25 01:12

crhaag


1 Answers

You need to increment i when you are performing your calculation.

def while11(nums,maxi):
    i=0
    total=0
    while total<=maxi:
        total+=nums[i]
        i+=1
    return total

Your function is simply taking the first value in a list and adding it until it is greater than the max value. You probably didn't notice this because in your first two cases, all values are the same. In your third case however, you have a list consisting of [10, 9, 8, 7, 6, 5, 4, 3, 2]. This should be taking 10 + 9 + 8 + 7... etc. until the max value, but your function is taking 10 + 10 + 10 + 10 .... etc. until the max value.

like image 98
Preston Martin Avatar answered Dec 04 '25 16:12

Preston Martin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!