Thoughtworks校招内推作业题解

2017-09-14  本文已影响0人  fairish

审题


纵观题目,我们就知道我们要实现的是一个简易的球馆计费系统,并没有涉及什么复杂的算法,最复杂的应该就是排序算法了吧2333

思路


对于每一条预定的“命令”,我们可以抽象出其基本的属性,成为一个“订单”,这就是我们解题设计的订单类。属性主要有有:
订单发起人、场馆、预定日期、预定时间、预定时长
输入的命令是字符串,因此需要对字符串进行解析,将其包装成对象,便于后续操作。包装成对象后,将对象加入到一个订单列表,并对列表进行实时维护,保证新的订单进来时,
重复预定重复取消预定的订单能够得到有效处理。最终统计订单的费用后,对场馆的收入进行汇总,将订单按照场馆、时间先后顺序 输出。

实现


处理时间第一想到是用Python或者Javascript,根据自己的情况我选择了Python.

from datetime import date

import math
pay_rule1 = [30,30,30,50,50,50,50,50,50,80,80,60,60]
pay_rule2 = [40,40,40,50,50,50,50,50,50,50,50,60,60]
booking = {"A":[],"B":[],"C":[],"D":[]} #用四个列表来分别存储各个场馆的订单
class Booking:
    def __init__(self,user,site,date_hour,h,cancel,pay_type,fee,dateStr, timeStr,day):
        self.user = user #用户
        self.site = site #场馆
        self.date_hour = date_hour #预定的日期时间,类型为整数
        self.h = h #预定时长
        self.cancel = cancel  #订单类型是否为取消
        self.pay_type = pay_type #支付类型,用于标记工作日还是周末,以采用不同的计费规则
        self.fee = fee #订单产生的费用
        self.dateStr = dateStr #日期,类型为字符串
        self.timeStr = timeStr #时间, 类型为字符串
        self.day = day #星期,用1~7代表周一到周日
    def __eq__(self, other):
        return self.user==other.user and self.date_hour==self.date_hour and self.h == other.h
    def c_fee(self):
        if self.cancel==True:
            if(self.pay_type==1):
                 self.fee *= 0.25
            else:
                self.fee *= 0.5
            self.fee = math.floor(self.fee)`
 def booking_sort():
    for c in ["A","B","C","D"]:
        booking[c] = sorted(booking[c], key=lambda book: book.date_hour)  # 根据时间排序 
def getDate(str):
    e = str.split("-")
    e[0] = int(e[0])
    e[1] = int(e[1])
    e[2] = int(e[2])
    return e
#获取开始时辰
def getStart(t):
    return int(t.split("~")[0].split(":")[0])
#结束时辰
def getEnd(t):
    return int(t.split("~")[1].split(":")[0])
#检查整点
def checkT(t):
    if t.split("~")[0].split(":")[1] != "00" or t.split("~")[0].split(":")[1] != "00" :
        return 1
    return 0
#将输入转换成对象处理
def format(data,l):
    canc = False
    if l==5:
        canc = True
        if(data[4]!="C"):
            #检测第五个字符合法性
            return {}
    user = data[0]
    da = getDate(data[1]) #时间日期数组
    d = date(da[0],da[1],da[2])
    dd = d.isoweekday()
    t = data[2]
    #检测时间是否为整点
    if checkT(t):
        return {}
    s = getStart(t)
    date_hour = da[0] * 1000000 + da[1] * 10000 + da[2] * 100 + s
    end = getEnd(t)
    h  = end - s
    #检测时间合法性
    if s>=end or s < 9 or end > 22:
        return {}
    pay = 0
    pay_type = 0 # 0为工作日,1为周末
    pay_rule = pay_rule1
    if (dd > 5):
        pay_type = 1
        pay_rule = pay_rule2
    for i in range(s, end):
        pay += pay_rule[i-9]
    #print(pay)
    e = Booking(user,data[3],date_hour,h,canc,pay_type,pay,d,t,dd)
    return e`
def add(e):
    flag = True
    l = len(booking[e.site])
    if l==0:
        flag = True
    else:
        for i in range(0,l):
            if e.date_hour==booking[e.site][i].date_hour and booking[e.site][i].cancel==False:
                flag = False
                break
            else:
                a1 = booking[e.site][i].date_hour
                a2 = booking[e.site][i].h + a1
                b1 = e.date_hour
                b2 = e.h + b1
                if booking[e.site][i].cancel==False and ((a2>b1 and b1 > a1)or(b2>a1 and b1<a1)):
                    flag = False
                    break
    if(flag):
        booking[e.site].append(e)
        return 0
    else:
        return 1

def cancel(e):
    flag = False
    l = len(booking[e.site])
    if (l == 0):
        flag = False
    else:
        for i in range(0, l):
            if e == booking[e.site][i] and booking[e.site][i].cancel==False:
                flag = True
                break
    if flag:
        i = booking[e.site].index(e)
        booking[e.site][i].cancel = True
        return 1
    else:
        return 0
def solve(command):
    data = command.split()
    l = len(data)
    if l==4:
        e = format(data,l)
        if(isinstance(e,Booking)):
            if(add(e)==0):
                print("> Success: the booking is accepted!")
            else:
                print("> Error: the booking conflicts with existing bookings!")
        else:
            print("> Error: the booking is invalid!")
    elif l==5:
        e = format(data,l)
        if(isinstance(e,Booking)):
            if(cancel(e)):
                print("> Success: the booking is accepted!")
            else:
                print("> Error: the booking being cancelled does not exist!")
        else:
            print("> Error: the booking is invalid!")
    else:
        print("> Error: the booking is invalid!")
def account():
    booking_sort()
    print("> 收入汇总")
    print("> ---")
    sum = cac()
    print("> ---")
    print("> 总计:"+str(sum)+"元")`
def cac():
    sum = 0
    for c in ["A","B","C","D"]:
        print("> 场地:"+c)
        l = len(booking[c])
        xj = 0
        item = booking[c]
        for i in range(0,l):
            flag = False
            if item[i].cancel==True:
                flag = True
            item[i].c_fee()
            xj += item[i].fee
            if flag:
                print(">",item[i].dateStr,item[i].timeStr,"违约金", str(item[i].fee)+"元")
            else:
                print(">",item[i].dateStr, item[i].timeStr,str(item[i].fee)+"元")
        sum += xj
        print("> ⼩计:"+str(xj)+"元")
        if c != "D":
            print ('>')
    return sum
if __name__ == '__main__':
    while(1):
        command = input("")
        if (command == ""):
            account()
            break
        else:
            solve(command)

测试

win10 *64 Python3.6.2下 (不兼容 Python2.7) 已通过测试用例1、2,并且输出格式已经校对多次,符合用例输出。可能有些边界情况没有考虑到

后记

其实很久没有用Python,写起来感觉手生,以至于对订单时间排序都要先将时间转换成 int(囧.jpg),感觉代码还有很多可以优化的地方,没眼严格遵循命名规则,类的设计存在冗余。“每多学一点知识”,就可以“少写一行代码”,已经成了我大四上学期的座右铭,一起共勉。

上一篇下一篇

猜你喜欢

热点阅读