您的位置:首页 > 编程语言 > Python开发

用Python写Pat上的题目,初战落败(问题已解决)

2017-06-21 21:24 246 查看
试着用python写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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python pat