如果这些数字的总和超过100,则打印出列表中的所有数字。

2024-04-27 00:15:24 发布

您现在位置:Python中文网/ 问答频道 /正文

数字列表nums并按顺序打印nums中的所有数字,直到打印的数字之和超过100。我需要使用while循环重写函数,我不能使用for、break或return。
如果数字之和小于或等于100,则打印列表中的所有数字。 下面是我对这个问题的尝试(这是错误的……),以及我想要达到的结果。 我想知道你对如何解决问题的想法,或者你对我的代码逻辑的建议。 提前多谢: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

Tags: the函数列表forindexreturn顺序数字
2条回答

我有一个代码,它也可以工作:

def solve(l):
    i=-1
    j=0
    cur=[]
    while (i<(len(l)-1) and sum(cur)<=100):
        i+=1
        j=l[i]
        if sum(cur)+j>100:
           pass
        print(j, end=" ")
        cur.append(j)
    print()
solve([100, -3, 4, 7])
solve([1, 2, 3])
solve([101, -3, 4, 7])

输出:

100 -3 4
1 2 3
101

这可能不是最优雅的方式,但考虑到你的限制,这是最好的-

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])

输出-

100 -3 4
1 2 3
101

相关问题 更多 >