2

我有一个包含货币值的字符串。
我必须从字符串中逐个字符地读取,并且函数必须返回result = 0所有val.

例如:string = "You Score is MX var."
哪里var 可以有这些值中的任何一个

[14 , 14.98 , 114 , 114.98 , 1116 , 1,116 , 1116.78 , 1,116.18 , 11,12,123 , 1,12,123.89 ... and so on...]

我的代码

def evaluate():
    result , count = 0 , 0
    dot , comma = False , False
    while (index_of_String < Len_of_string):
        ch = string[index_of_String]        
        if (ch == '.'):
            if (dot == True):
                break ;                
            dot = True            
        elif (ch == ','):
            if (dot == True):
                break            
            comma = True             
        elif not (ch >= '0' and ch <= '9'):
            if not (ch == ' ' or ch == ','):                
                result = -1            
            break
        else:
            if (dot == False):
                count += 1
        print ("Char %c" % ch)
        index_of_String += 1        

    print ("count of numeric digits %d" % count)
    if (result == 0):
        if dot == False:
            result = -1
        if comma == False:
            if (count > 3):
                result = -1

    return (result, index_of_String)

所需输出

string = "You Score is MX 14."
result = 0

string = "You Score is MX 14.89."
result = 0

string = "You Score is MX 1114.89."
result = 0

string = "You Score is MX 1,114.89."
result = 0  

string = "You Score is MX 11,,,14.89."
result = -1 (fail)

string = "You Score is MX 11.14.89."
result = -1 (fail)

string = "You Score is MX 1,114.89."
result = 0  

string = "You Score is MX 1,14.89."
result = -1 (fail)

string = "You Score is MX 1,11,114.89."
result = 0

我需要进行哪些修改才能使我的代码适用于所有这些情况。
有帮助修改吗??

4

2 回答 2

0

如果你真的需要逐个字符地去,那么:

def evaluate(string, values):
    value = []
    for char in string:
        if char.isdigit() or char in ',.':
            value.append(char)
    value = ''.join(value).strip('.,')
    return int(value in values)

测试

>>> values = ['14', '14.98', '114', '114.98', '1,116.5']
>>> string = 'You Score is MX 14.98.'
>>> evaluate(string, values)
1
string = 'You Score is MX 115.' # 115 is not in values
>>> evaluate(string, values)
0
于 2013-04-23T21:33:14.820 回答
0

如果 char by char 不是必需的,则:

def evaluate(string, values):
    for word in string.rstrip('.').split():
        if word in values:
            return False
    return True

测试:

>>> values = map(str, [14 , 14.98 , 114 , 114.98 , 1116])
['14', '14.98', '114', '114.98', '1116']
>>> string = 'You Score is MX 14.98.'
>>> evaluate(string, values)
False
string = 'You Score is MX 115.' # 115 is not in values
>>> evaluate(string, values)
True
于 2013-04-23T14:55:03.587 回答