Reputation: 2950
I want integer input for the variable x
, space separated. User input example 20 15 7 5 4 2
. This list should be entered into x
and then split into two parts. The parts should be then substracted with each other and output the smallest possible difference. The below code splits the input already partially into to lists but it does not complete it. I thought I would either create a while loop encapsulating all if-statements which however gives me the following error.
Error message
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
I assume the while statement does not stop and attempts after a while to loop over an empty list of variable x
. Initially, I thought to check the length of the x
variable prior starting the while loop again but that does not work. The if-statement in the second while-loop also does not help even if I indent it to include it in the while loop.
# 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
Can somebody please explain me first, whether the issue is here my while loop and if so, second, how I can exit the while loop once there are no values in x
anymore?
Upvotes: 1
Views: 347
Reputation: 342
You need to split the user input into separate strings before mapping int
onto it. Otherwise, it tries to convert the whole string of 20 15 7 5 4 2
into one integer value. To fix this, try adding a split()
to the map input to convert it to a list of strings:
x = list(map(int, ui.split())
EDIT: I was mainly pointing out the problem that caused the error, but the bigger problem is probably the infinite loop as mentioned above.
Upvotes: 1
Reputation: 46
you need to add a condition so it exits the loop when x is no longer valid:
# 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)
Upvotes: 2