chuddles - 1 year ago 58

Python Question

List of numbers nums and prints all the numbers from nums in order until the sum of the numbers printed exceeds 100. I need to rewrite the function using a while loop and **I cannot use for, break or return.**

if the sum of the numbers is less than or equal to 100 then all numbers in the list are printed.

Below includes my attempt of the question (which is wrong...), and the outputs I would like to achieve.

I would like to know your ideas on how you would try to solve the problem or your advice on the logic of my code.

Many thanks in advance :D

`def print_hundred(nums):`

""" Hundy club """

total = 0

index = 0

while index < nums[len(nums)]:

print(nums)

total += nums[index]

else:

if total > 100:

print(total)

print_hundred([1, 2, 3])

print_hundred([100, -3, 4, 7])

print_hundred([101, -3, 4, 7])

test1 (Because the sum of those numbers are still less than 100)

1

2

3

test2 (100 - 3 + 4 = 101, so the printing stops when it exceeds 100)

100

-3

4

test3 (Already exceeds 100)

101

Answer Source

This may not be the most elegant way to do this, but given your constraints, this is as good as it gets -

```
def solve(arr):
index = 0
total = 0
end = len(arr)
flag = False
while index < len(arr) and not flag:
total += arr[index]
index += 1
if total > 100:
end = index
flag = True
print(*arr[0:end], sep = ' ')
solve([100, -3, 4, 7])
solve([1, 2, 3])
solve([101, -3, 4, 7])
```

Output -

```
100 -3 4
1 2 3
101
```