python - ValueError: invalid literal for int() with base 10: '40 1 3 4 20\n'
问题描述
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'
解决方案
您正在错误地读取输入。尝试这个:
Numbers = [int(x) for x in sys.stdin.read().strip().split(' ')]
推荐阅读
- reactjs - 如何在无状态的条件外部反应组件中返回传递和返回变量?
- python - 为什么这个简单的 3 行程序不起作用?
- python - 像列表一样生成字典值
- php - Laravel 5.5 控制台电视条形图高图表多个数据集和标签
- django - 带有 2 个模型的 Django 内联模型表单集
- javascript - 如何将 ng-repeat 项目连续放置?
- ios - 如何在 Swift 中使用 WKwebView 制作活动指示符
- react-native - react-native 版本 0.55.4 和 0.56.0 的问题
- mysql - MySql 查询根据今天的日期选择用户
- sql-server - 使用 SQL Server 执行存储过程时出错