crhaag
crhaag

Reputation: 45

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.

Upvotes: 3

Views: 6851

Answers (3)

Patrick Haugh
Patrick Haugh

Reputation: 61032

You need to change the value of i in your while loop:

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

Otherwise it will always add the first value to total

Upvotes: 1

Preston Martin
Preston Martin

Reputation: 2963

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.

Upvotes: 1

finmor
finmor

Reputation: 451

You have forgotten to update the i variable on every iteration. You keep adding the num[0] element

Upvotes: 0

Related Questions