首页 文章

如果这些数字的总和超过100,则打印出列表中的所有数字 . [关闭]

提问于
浏览
-2

数字列表按顺序打印和打印所有数字,直到打印数字的总和超过100.我需要使用while循环重写函数 I cannot use for, break or 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

2 回答

  • 0

    我有这个代码也有效:

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

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

    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
    

相关问题