【问题标题】:From while loop to ValueError从 while 循环到 ValueError
【发布时间】: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


    【解决方案1】:

    在将int 映射到它之前,您需要将用户输入拆分为单独的字符串。否则,它会尝试将20 15 7 5 4 2整个 字符串转换为一个整数值。要解决此问题,请尝试将 split() 添加到地图输入以将其转换为字符串列表:

    x = list(map(int, ui.split())
    

    编辑:我主要是指出导致错误的问题,但更大的问题可能是上面提到的无限循环。

    【讨论】:

      【解决方案2】:

      您需要添加一个条件,以便在 x 不再有效时退出循环:

      # User input, space separated
      ui = input()
      x = list(map(int, ui.split(' ')))
      half = sum(x)//2
      
      # two empty lists to enter the x-values
      a = []
      b = []
      
      # while len(x) != 0:
      # while loop to divide the values
      while len(x) > 1:
          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))
      
      # check last element independently
      if sum(b) < sum(a) < half:
          b.append(x.pop())
      else:
          a.append(x.pop()) 
      
      print(x)
      print(a)
      print(b)
      

      【讨论】:

      • 感谢您的建议,但现在我在x 中还剩下一个值。你知道我如何在ab 中获得最后一个值吗?
      • 不确定,但可能类似于上面的更新。祝你好运! ``` 输入:20 15 7 5 4 2 输出:[] [20, 5, 2] [15, 7, 4] ``
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-27
      • 2012-09-19
      • 1970-01-01
      相关资源
      最近更新 更多