简体   繁体   English

Codeeval挑战未返回正确的输出。 (蟒蛇)

[英]Codeeval Challenge not returning correct output. (Python)

So I started doing the challenges in codeeval and i'm stuck at an easy challenge called "word to digit" 因此,我开始进行编码时代的挑战,而我陷入了一个简单的挑战,即“单词到数字”

This is the challenge description: 这是挑战说明:

Having a string representation of a set of numbers you need to print this numbers. 具有一组数字的字符串表示形式,您需要打印此数字。 All numbers are separated by semicolon. 所有数字均以分号分隔。 There are up to 20 numbers in one line. 一行中最多有20个数字。 The numbers are "zero" to "nine" 数字是“零”到“九”

input sample: 输入样本:

zero;two;five;seven;eight;four 零;二;五;七;八;四

three;seven;eight;nine;two 三;七;八;九;两个

output sample: 输出样本:

025784 025784

37892 37892

I have tested my code and it works, but in codeeval the output is always missing the last number from each line of words in the input file. 我已经测试了我的代码,并且可以正常工作,但是在codeeval中,输出始终缺少输入文件中每行单词的最后一个数字。

This is my code: 这是我的代码:

import sys

def WordConverter(x):
    test=str()
    if (x=="zero"):
        test="0"
    elif (x=="one"):
        test="1"
    elif (x=="two"):
        test="2"
    elif (x=="three"):
        test="3"
    elif (x=="four"):
        test="4"
    elif (x=="five"):
        test="5"
    elif (x=="six"):
        test="6"
    elif (x=="seven"):
        test="7"
    elif (x=="eight"):
        test="8"
    elif (x=="nine"):
        test="9"
    return (test)

t=str()
string=str()
test_cases=open(sys.argv[1],'r')
for line in test_cases:
    string=line.split(";")
    for i in range(0,len(string)):
        t+=WordConverter(string[i])
    print (t)
    t=str()

Am I doing something wrong? 难道我做错了什么? Or is it a Codeeval bug? 还是Codeeval错误?

When iterating over the lines of a file with for line in test_cases: , each value of line will include the newline at the end of the line (if any). 当在与文件的行迭代for line in test_cases: ,的每个值line将包括在该行(如果有的话)的端部的换行。 This results in the last element of string having a newline at the end, and so this value won't compare equal to anything in WordConverter , causing an empty string to be returned. 这导致string的最后一个元素的string有换行符,因此该值将不等于WordConverter任何WordConverter ,从而导致返回空字符串。 You need to remove the newline from the string at some point. 您有时需要从字符串中删除换行符。

You just need to remove the newline char from the input. 您只需要从输入中删除换行符即可。 Replace: 更换:

string=line.split(";")

With

string=line.strip().split(";")

However, using string as the variable name is not a good decision... 但是,使用string作为变量名并不是一个好的决定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM