Here I am required to use REGEX to do the stock price program, yet I found it almost impossible for me to do, I can only deal with for loop.
'''Parse Stock prices. Create a function that will
decode the old-style fractional stock price. The price
can be a simple floating point number or it can be a
fraction, for example, 4 5/8.
Develop two patterns, one for numbers with optional
decimal places and another for a number with a space
and a fraction. Write a function that accepts a string
and checks both patterns, returning the correct decimal
price for whole numbers (e.g., 14), decimal prices
(e.g., 5.28) and fractional prices (27 1/4).
For the fractional prices (27 1/4), only whole numbers
are allowed in it, and the fractional part must be proper,
that is, it must in the (0,1) range, excluding 0 and 1.
Otherwise, your fuction should return float('nan'),
that is, Not-A-Number.
return a float type object representing the parsed price.
For example,
stock_price('27 1/4') returns float('27.25')
stock_price('27 4/2') returns float('nan')
stock_price('1/2') returns float('0.5')
stock_price('half') returns float('nan')
stock_price('0.1/0.2') returns float('nan')
stock_price('0.2') returns float('0.2')
stock_price('2') returns float('2')
'''
def stock_price(price):
if price.count('.')==1:
while price.count('/')==0:# 如果有'.'和'/',那么pretest将其输出为'nan'
return float(price) #如果有'.'没有'/',那么就是直接转为float
return float('nan')
elif price.count('.')==0:
if price.count('/')==1:#如果没有'.',有'/'
b=price.find('/') #找到'/'和 ' '所在的位置(如果有' '的话)
c=price.find(' ')
if price[b-1]<price[b+1] and price.count(' ')==1:#前面的数字小于后面的数字
return float(int(price[:c])+int(price[c+1:b])/int(price[b+1:]))
#找到位置后,将string分开并且转成int,此时有' ',那么将' '前面的数字和后面'/'
#前后的数字相除即可
elif price[b-1]<price[b+1] and price.count(' ')==0:#前面的数字小于后面的数字
return float(int(price[:b])/int(price[b+1:]))
#如果没有' ',那么直接将'/'前后的数字相除即可
else:
return float('nan')
#如果'/'前面的数字大于后面的数字,就输出'nan'
elif price.count('/')==0: #既没有'.'也没有'/'
if price.isdigit()==True:#如果是数字,没有' '
return float(price)
else: #如果不是数字,包括其中包含' '
return float('nan')
else: # 多于两个'.的输入一定无效
return float('nan')