I have a String which contains a Currency Value.
I have to read character by character from string and function must return result = 0
for all values of val
.
Ex: string = "You Score is MX var."
Where var
can have any of these values
[14 , 14.98 , 114 , 114.98 , 1116 , 1,116 , 1116.78 , 1,116.18 , 11,12,123 , 1,12,123.89 ... and so on...]
MY CODE
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)
Required Output
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
What modification(s) do I need to make my code works for all these cases.
Any Help in modifying??
If char by char is not a requirement then:
def evaluate(string, values):
for word in string.rstrip('.').split():
if word in values:
return False
return True
Test:
>>> 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
If you really need to go char by char then:
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)
Test
>>> 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.