【问题标题】:NZEC in python on spoj for AP2NZEC in python on spoj for AP2
【发布时间】:2012-12-08 20:02:15
【问题描述】:

我写了以下两个代码

FCTRL2.py

​​>
import sys;
def fact(x):
    res = 1
    for i in range (1,x+1):
        res=res*i
    return res;

t = int(raw_input());
for i in range (0,t):
    print fact(int(raw_input()));

AP2.py

​​>
import sys;

t = int(raw_input());
for i in range (0,t):
    x,y,z = map(int,sys.stdin.readline().split())
    n = (2*z)/(x+y)
    d = (y-x)/(n-5)
    a = x-(2*d)
    print n
    for j in range(0,n):
        sys.stdout.write(a+j*d)
        sys.stdout.write(' ')
    print' '

FCTRL2.py 在 spoj 上被接受,而 AP2.py 给出 NZEC 错误。两者都可以在我的机器上正常工作,并且我发现两者的返回值没有太大区别。请解释两者有什么区别以及如何避免 AP2.py 的 NZEC 错误

【问题讨论】:

    标签: python-2.7 return return-value


    【解决方案1】:

    输入中可能有额外的空格。一个好的问题设置器会确保输入满足指定的格式。但由于 spoj 几乎允许任何人添加问题,因此有时会出现这样的问题。缓解空白问题的一种方法是立即读取输入,然后对其进行标记。

    import sys;   # Why use ';'? It's so non-pythonic.
    
    inp = sys.stdin.read().split()    # Take whitespaces as delimiter
    t = int(inp[0])
    readAt = 1
    for i in range (0,t):
        x,y,z = map(int,inp[readAt:readAt+3])    # Read the next three elements
        n = (2*z)/(x+y)
        d = (y-x)/(n-5)
        a = x-(2*d)
        print n
        #for j in range(0,n):
        #    sys.stdout.write(a+j*d)
        #    sys.stdout.write(' ')
        #print ' '
        print ' '.join([str(a+ti*d) for ti in xrange(n)]) # More compact and faster
        readAt += 3   # Increment the index from which to start the next read
    

    【讨论】:

      【解决方案2】:

      第 10 行的 n 可以是浮点数,范围函数需要一个整数。因此程序以异常退出。

      我在 Windows 上测试了这个值:

      >ap2.py
      23
      4 7 9
      1.6363636363636365
      Traceback (most recent call last):
        File "C:\martin\ap2.py", line 10, in <module>
          for j in range(0,n):
      TypeError: 'float' object cannot be interpreted as an integer
      

      【讨论】:

      • 输入将始终确保 n 为整数。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多