【问题标题】:while loop doesn't stop the loop when the expression is false当表达式为假时,while循环不会停止循环
【发布时间】:2021-09-21 03:21:07
【问题描述】:

代码应该在 price_t

测试用例

7 50 \n
1 12 5 111 200 1000 10
first_multiple_input = input().rstrip().split()

n = int(first_multiple_input[0])

k = int(first_multiple_input[1])

prices = list(map(int, input().rstrip().split()))

prices=sorted(prices)
price_t=0
count=0
while price_t <= k:
    for i in range(len(prices)):
        price_t=price_t+prices[i]
        count+=1
    print(count )

【问题讨论】:

  • 如果条件被破坏,你应该终止 for 循环。
  • 在外循环再次检查条件之前,您的内循环将完整运行。然后,如果条件不满足,它将再次运行内循环完全通过,然后再次检查条件
  • 可能您想迭代 for price in prices 并在循环内累积每个连续的 priceif price_t &lt;= k 并在达到阈值后跳过其余部分。
  • @G.Anderson 非常感谢您!你的回答正是我需要知道的。

标签: python while-loop


【解决方案1】:

如果我这样重写你的循环,是不是更清楚发生了什么?

while price_t <= k:
    for price in prices:
        price_t += price

仅当price_t 小于k 时,外部循环才会运行。但随后内部循环将运行每个价格的价格

你想要的大概是:

for price in prices:
    if price_t > k:
        break
    price_t += k

【讨论】:

  • 谢谢,是的,我就是这个意思
猜你喜欢
  • 1970-01-01
  • 2020-07-21
  • 2020-08-19
  • 2016-06-21
  • 1970-01-01
  • 2015-12-30
  • 2021-08-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多