【发布时间】:2019-07-19 10:00:12
【问题描述】:
我想要变量x 的整数输入,空格分隔。 用户输入示例 20 15 7 5 4 2。这个列表应该输入x,然后分成两部分。然后应该将这些部分相互减去并输出最小的可能差异。下面的代码将已经部分输入的输入拆分为列表,但它没有完成它。我以为我会创建一个封装所有 if 语句的 while 循环,但这会给我以下错误。
错误信息
Traceback (most recent call last):
File "C:/Users/Array Partitioning.py", line 28, in <module>
arrpartitioning(input().split())
File "C:/Users/Array Partitioning.py", line 18, in arrpartitioning
b.append(max(x))
ValueError: max() arg is an empty sequence
我假设 while 语句不会停止,并在一段时间后尝试循环遍历变量 x 的空列表。最初,我想在再次启动 while 循环之前检查 x 变量的长度,但这不起作用。即使我缩进它以将其包含在 while 循环中,第二个 while 循环中的 if 语句也无济于事。
# User input, space separated
ui = input()
x = list(map(int, ui)
half = sum(x)//2
# two empty lists to enter the x-values
a = []
b = []
flag = False
# while len(x) != 0:
# while loop to divide the values
while flag == False:
if sum(a) < half:
a.append(max(x))
x.remove(max(x))
while sum(b) < sum(a):
b.append(max(x))
x.remove(max(x))
# Same error message even if I indent the if-statement to the while-block
if len(x) == 0:
flag == True
有人可以先解释一下,问题是否出在我的 while 循环中,如果是这样,第二,一旦x 中不再有值,我该如何退出 while 循环?
【问题讨论】:
标签: python python-3.x list while-loop