Python - 读取文件名的路径

时间:2014-02-22 08:06:02

标签: python argv

我正在Python中尝试这个Code Eval挑战,名为Predict the Number:

https://www.codeeval.com/open_challenges/125/

我的问题(我认为)与读取输入文件有关。它说“你的程序应该接受第一个参数作为文件名的路径。” AFAIK,读取这样的文件涉及import sys和sys.argv [1]。它测试正常,但提交失败。我认为我的代码没有逻辑错误,但在这里它是。也许我没有正确使用argv ......?

编辑:当我提交时,我收到以下错误:“CodeEval错误:进程在10秒后中止。”这只是意味着我的代码效率太低而无法完成吗?

import sys

# increment the given int, returns 0, 1, or 2
def inc(num):
    return (num + 1) % 3

# double the length of the input sequence by incrementing
# each int from old half to create the new half
def double(old):
    new = ''
    for i in old:
        new += str(inc(int(i)))
    return old + new

# returns the int (0, 1, or 2) of the input index
def position(n):
    global sequence
    while len(sequence) < n:
        sequence = double(sequence)
    return int(sequence[n])

# print each int in the given position of each line in the file
def predict(filename):
    file = open(filename, 'r')
    for line in file.readlines():
        if len(line) > 0:
            print position(int(line))
    file.close()

# initialize the sequence
sequence = '0'

# call the program with the first command-line argument
predict(sys.argv[1])

# clean exit
sys.exit(0)

0 个答案:

没有答案