ValueError: invalid literal for int() with base 10: '40 1 3 4 20\n'

Viewed 701

Programming challenge description:

Alice has invented a new card game to play with Bob. Alice made a deck of cards with random values between 1 and 52. Bob picks 5 cards. Then, he has to rearrange the cards so that by utilizing the operations plus, minus, or times, the value of the cards reach Alice's favorite number, 42. More precisely, find operations such that:

((((val1 op1 val2) op2 val3) op3 val4) op4 val5) = 42

import sys
import itertools
Numbers=[]
i=0
for line in sys.stdin:
    # print(line, end="")
    Numbers.append(int(line))
    i=i+1
    if(i==5):
        break


Operators=['+','-','*','+','-','*'] #we can be use 4 operator from this

#file all the posible permutations
lst1=list(itertools.permutations(Numbers,5))
lst2=list(itertools.permutations(Operators,4))

result = False
for x in lst1:
    for op in lst2:
        str1=str(x[0])+op[0]+str(x[1])
        str2=str(str1)+op[1]+str(x[2])
        str3=str(str2)+op[2]+str(x[3])
        str4=str(str3)+op[3]+str(x[4])
        exp=eval(str4) #solve the expression

        if(exp==42):
            result = True
            break
    if(result==True):
        break

if(result==True):
    print("\nYES")
else:
    print("\nNO")

Using an online IDE to run this but getting an error. Please tell me where I made the mistake. The error is:

Traceback (most recent call last):
  File "/tmp/source.py", line 8, in <module>
    Numbers.append(int(line))
ValueError: invalid literal for int() with base 10: '40 1 3 4 20\n'
2 Answers

You are reading the input incorrectly. Try this:

Numbers = [int(x) for x in sys.stdin.read().strip().split(' ')]

The argument you are passing to the int function is a string with spaces and so it can't be converted to a string. If you want to add all the numbers in the line in the array, you can do -

Numbers.extend(list(map(int, line.split())))
Related