用Python写Pat上的题目,初战落败(问题已解决)
2017-06-21 21:24
246 查看
试着用python写PAT上题目,但遇上了个问题。本地测试正常,提交代码,结果返回为零,得分为零。网上查了一下,也没找到解决办法。
Input
Each input file contains one test case. Each case contains a pair of integers a and b where -1000000 <= a, b <= 1000000. The numbers are separated by a space.
Output
For each test case, you should output the sum of a and b in one line. The sum must be written in the standard format.
Sample Input
-1000000 9
Sample Output
-999,991
返回非零,得分为0
同时上面的代码,算法上也有问题。做了相应的修改。以下代码能在pat上得到正确的测试结果。
题目 1001. A+B Format (20)
Calculate a + b and output the sum in standard format – that is, the digits must be separated into groups of three by commas (unless there are less than four digits).Input
Each input file contains one test case. Each case contains a pair of integers a and b where -1000000 <= a, b <= 1000000. The numbers are separated by a space.
Output
For each test case, you should output the sum of a and b in one line. The sum must be written in the standard format.
Sample Input
-1000000 9
Sample Output
-999,991
编写的代码
a = int(raw_input())#input()也试过 b = int(raw_input()) s = a + b m=abs(s) n = m % 1000 m = m / 1000 out = str(n) while (m): n = m % 1000 out = str(n) + ',' + out m = m / 1000 if s < 0: out = '-' + str(out) print (out) exit(0)#看知乎上有人说加了这个就可以,但我这里还是不行
提交结果
本地编译器上试了一下,明明可以。但提交代码后的结果却是:返回非零,得分为0
问题发现
最后发现代码的主要问题在于读入。python的raw_input是已回车作为间隔的,而非空格。同时上面的代码,算法上也有问题。做了相应的修改。以下代码能在pat上得到正确的测试结果。
a,b = (int(x) for x in raw_input().split(' ')) s = a + b if s==0: print ('0') exit(0) m = abs(s) out='' while (m): n = m % 1000 str_n=str(n) while(len(str_n)<3 and m>=1000): str_n='0'+str_n out = str_n + ',' + out m = m / 1000 if s < 0: out = '-' + str(out) out=out[:-1] if not out: out='0' print (out) exit(0)
相关文章推荐
- PAT 1007. 素数对猜想 python 运行超时问题解决方案
- 用Python解决Pat上的题目,二战成功
- 原文链接:http://yuren.space/blog/2016/07/31/python如何解决汉字编码问题/
- python代码中碰到的问题及解决
- python “UnicodeEncodeError: 'gbk' codec can't encode character问题解决。
- 解决python中matplotlib绘图中文显示问题
- CentOS6.5上python-mysql环境的安装问题解决
- pycharm 使用心得(九)解决No Python interpreter selected的问题
- Python的问题解决: IOError: [Errno 32] Broken pipe
- Python字符串的encode与decode研究心得——解决乱码问题
- Python连接mssql数据库编码问题解决方法
- CentOS解决因python升级导致的中文输入法无法正常使用的问题
- 用python解决汉诺塔问题
- python问题:IndentationError:expected an indented block错误解决
- Python:解决中文字符串问题
- python robotframework用法及"wxpython not found"和“no browser is open”问题解决
- python学习笔记——5_解决问题编写脚本
- python 字典对象赋值之deepcopy遭遇的问题及解决过程(lxml惹的祸)
- Python 小问题解决
- PAT 1008. 数组元素循环右移问题 返回非零 python