为什么我的代码会出现NZEC运行时错误?

时间:2009-10-03 22:28:03

标签: python

Question source: SPOJ.. ORDERS

def swap(ary,idx1,idx2):
    tmp = ary[idx1]
    ary[idx1] = ary[idx2]
    ary[idx2] = tmp

def mkranks(size):
    tmp = []
    for i in range(1, size + 1):
        tmp = tmp + [i]
    return tmp

def permutations(ordered, movements):
    size = len(ordered)
    for i in range(1, size): # The leftmost one never moves
        for j in range(0, int(movements[i])):
            swap(ordered, i-j, i-j-1)
    return ordered

numberofcases = input()
for i in range(0, numberofcases):
    sizeofcase = input()
    tmp = raw_input()
    movements = ""
    for i in range(0, len(tmp)):
        if i % 2 != 1:
            movements = movements + tmp[i]
    ordered = mkranks(sizeofcase)
    ordered = permutations(ordered, movements)
    output = ""
    for i in range(0, sizeofcase - 1):
        output = output + str(ordered[i]) + " "
    output = output + str(ordered[sizeofcase - 1])
    print output

1 个答案:

答案 0 :(得分:1)

让您的代码更加Pythonic(但不改变其流程/算法):

def swap(ary, idx1, idx2):
    ary[idx1], ary[idx2] = [ary[i] for i in (idx2, idx1)]

def permutations(ordered, movements):
    size = len(ordered)
    for i in range(1, len(ordered)):
        for j in range(movements[i]):
            swap(ordered, i-j, i-j-1)
    return ordered

numberofcases = input()
for i in range(numberofcases):
    sizeofcase = input()
    movements = [int(s) for s in raw_input().split()]
    ordered = [str(i) for i in range(1, sizeofcase+1)]
    ordered = permutations(ordered, movements)
    output = " ".join(ordered)
    print output

我看到它在您指明的SPOJ URL中给出的示例案例中正确运行。你的失败案例是什么?