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

33 篇文章 0 订阅

试着用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)
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值