class Item:
def __init__(self, name, id, price):
self.name = name
self.id = id
self.price = price
def getName(self):
return self.name
def getId(self):
return self.id
def getPrice(self):
return self.price
def __str__(self):
return str(self.name) + " " + str(self.id) + " " + str(self.price)
class Shipment:
def __init__(self, id):
self.id = id
self.items = []
def getId(self):
return self.id
def getItems(self):
return self.items
def addItem(self, Item):
self.items.append(Item)
def __str__(self):
if self.items == []:
return str(self.id) + ": []"
else:
returnvalue = str(self.id) + ": ["
ctr = 0
while ctr < len(self.items) - 1:
returnvalue += str(self.items[ctr]) + ","
ctr += 1
returnvalue += str(self.items[len(self.items) - 1])
return returnvalue + "]"
class ItemException:
def __init__(self, message):
self.message = message
self.items = []
def __str__(self):
return str(self.message)
def main(list):
shipment = []
ctr = 0
while ctr < len(list):
list[ctr] = list[ctr].replace("\n" , "")
ctr += 1
ctr2 = 0
while ctr2 < len(list):
if list[ctr2].isdigit():
ship = Shipment(list[ctr2])
shipment.append(ship)
else:
split = list[ctr2].split()
if "$" not in list[ctr2]:
if len(split) != 2:
raise ItemException("Invalid name")
if "-" in list[ctr2]:
raise ItemException("Price can't be negative")
if ((len(split)) != 1):
if ctr2 != len(list):
item = Item(split[0], split[1], list[ctr2 + 1])
ship.addItem(item)
temp = list[ctr2].count(".")
if temp > 1:
raise ItemException("Invalid price, more than one .")
#need to add exception for more than 2 digits past the decimal point
ctr2 += 1
return shipment
我需要弄清楚如果价格'$ 4.567 \ n'的小数点后有两位以上的位数,则如何为此测试引发异常:
def test16():
result = False
try:
main(['55555555\n','socks 12345\n','$4.567\n','socks 12345\n','$4.56\n'])
except ItemException:
result = True
print result
return result
我想我需要拆分它,但是我不确定如何只隔离价格,然后拆分它以获取小数点后的数字。一旦达到这一点,我认为如果美分> 2引发ItemException,我可以做。
最佳答案
您将其拆分是正确的。你可以试试:
>>> '$4.587'.split('.')
['$4', '568']
>>> len('$4.587'.split('.')[1]) > 2
True
第二个条件检查点后的位数是否大于2。