CH 15 ToDoList Class

Huisu·2021년 12월 5일
0

Python

목록 보기
15/17
post-thumbnail

Read Me

Function

  • makeRecord
    • 동작: 주어진 입력 파라메타를 사용하여 List에 입력 받은 순서대로 저장하고, return 값으로 해당 List를 전달함
    • 입력 파라메타: 담당자이름, 종료기한(Deadline), 수행항목번호, 우선순위
      • 담당자이름: 문자열
      • 종료기한: 문자열, 년월일을 나타내는 8글자 (예: 20200718), 편의상 모든 월은 31일을 가짐
      • 수행항목번호: 문자열, 알파벳과 숫자로 이루어진 4글자 (예: A001)
      • 우선순위: 정수 숫자, 1/2/3 중 하나의 값
    • Return 값: 입력 파라메타를 순서대로 저장한 List (예: [“drsungwon”, “20200718”, “A001”, 1])
  • checkDeadline
    • 동작: 수행항목의 종료기한이 제대로 설정되어 있는지 확인하여, 사안별 return 값을 전달함
    • 입력 파라메타: makeRecord로 만들어진 List, 오늘 날짜를 나타내는 문자열 (예: “20200718”)
    • Return 값: 사안별로 다음의 값 중 하나를 return 함 (아래 사안들에 대해서, 위에서 아래로 조건을 검사하도록 함)
      • False: List에 저장된 항목의 종료기한이 문자열이 아닌 경우
      • -1: List에 저장된 항목의 종료기한이 2020년이 아닌 경우
      • -2: List에 저장된 항목의 종료기한이 잘못된 월을 가진 경우 (월이 1~12 사이의 값이 아닌 경우)
      • -3: List에 저장된 항목의 종료기한이 잘못된 일을 가진 경우 (일이 1~31 사이의 값이 아닌 경우)
      • -4: List에 저장된 항목의 종료기한이 오늘 보다 이전의 날자로 이미 지난 경우
      • True: List에 저장된 항목의 종료기한에 문제가 없는 경우
  • checkPriority
    • 동작: 수행항목의 우선순위가 제대로 설정되어 있는지 확인하여, 사안별 return 값을 전달함
    • 입력 파라메타: makeRecord로 만들어진 List
    • Return 값: 사안별로 True 혹은 False
      • True: List에 저장한 항목의 우선순위가 정수 1/2/3 중 하나의 값으로 정상적인 경우 (1이 제일 높은 우선순위임)
      • False: List에 저장한 항목의 우선순위가 정수 1/2/3이 아닌 타입 혹은 값으로 설정된 비정상적인 경우

ToDoList Class

  • addItem
    • 동작: 입력 파라메타의 작업의 수행항목번호에 문제가 없는 경우, 관리할 작업 정보로 등록함
    • 입력 파라메타: 신규로 등록할 작업 정보가 담긴 리스트 (makeRecord의 return 값)
    • Return 값:
      • False: 내부적으로 입력 파라메타에 대해서 checkDeadline과 checkPriority을 수행하여 정상적이지 않은 입력 파라메타를 받은 것으로 판단한 경우와 기존에 등록한 작업 중 수행항목번호가 중첩되는 경우임. 입력 파라메타의 작업 등록을 수행하지 않음
      • 정수: 신규 작업을 포함하여, 등록된 전체 작업 항목의 갯수
  • getEarliestItem
    • 동작: 가장 빠르게 처리되어야 하는 작업을 찾음
    • 입력 파라메타: 없음
    • Return 값: 현재에서 가장 가까운 날짜에 완료되어야 하는 작업의 수행항목번호. 같은 Deadline을 갖는 항목들이 있는 경우는, 우선순위가 높은 작업을 return 함. Deadline과 우선순위가 같은 경우는 먼저 등록된 작업을 return 함
  • getItemByName
    • 동작: 담당자가 담당하는 작업들의 수행항목을 빨리 마쳐야 하는 순서가 앞선 형태로 추출함
    • 입력 파라메타: 담당자이름 (문자열)
    • Return 값:
      • False: 담당자 이름에 대해서 등록된 작업이 없는 경우
      • 리스트: 담당자 이름으로 등록된 작업들의 수행항목번호들을 포함함. 종료시한이 가까운 항목들부터 먼 순서로 정렬되어 있음. 종료시한이 같은 경우는 우선순위가 높은 것이 먼저 나타나며 (낮은 인덱스), 종료시한과 우선순위가 같은 경우는 먼저 등록된 작업이 먼저 나타남
  • getItemsByEDF
    • 동작: 관리 중인 모든 작업에 대한 정보를 순서대로 추출함
    • 입력 파라메타: option으로 True 혹은 False임
    • Return 값: 등록된 모든 작업의 정보를 list in list로 return 함. 각 작업은 makeRecord를 통해서 만든 형태임. option이 True이면 Deadline이 가까운 항목이 낮은 인덱스를 갖음. Deadline이 같은 경우는 우선순위가 높은 항목이 낮은 인덱스를 가짐. Deadline과 우선순위가 같은 경우는 먼저 등록된 작업이 낮은 인덱스를 갖음. option이 False이면, True인 경우와 반대의 순서로 정렬된 정보를 list in list로 return 함
  • getItemDeadline
    • 동작: 특정 작업의 Deadline 날자를 조회함
    • 입력 파라메타: 조회하고자 하는 수행항목번호 (문자열)
    • Return 값: 수행항목번호의 Deadline (문자열) 혹은 수행항목번호가 등록되지 않은 경우는 False
  • deferDeadline
    • 동작: 특정 작업에 대한 Deadline을 최소1일~최대14일 지연시킴
    • 입력 파라메타: Deadline 일정을 지연시키고 싶은 수행항목번호와, 지연 날자 수 (1~14일 한도내에서만 지연 가능함)
    • Return 값: 해당 수행항목번호에 대해서 지연된 날자를 나타내는 문자열
  • writeFile
    • 동작: 등록되어 관리중인 작업 정보를 output.csv 화일에 저장함
      • 한 줄에 하나의 작업을 담당자이름, 종료기한, 수행항목번호, 우선순위 순서로 쉼표로 구분하여 저장함 (예: drsungwon,20200731,A001,1)
      • 한 줄의 끝은 줄 바꿈으로 바꿈
      • 화일에 저장하는 작업의 순서는 deadline이 가장 가까운 항목을 먼저 저장하며, deadline이 같다면 우선순위가 높은 작업을 먼저 저장함. deadline과 우선순위가 같은 항목은, 먼저 등록된 항목을 먼저 저장함. 즉, getItemsByEDF(True)의 결과에 해당하는 내용을 저장함
    • 입력 파라메타: 없음
    • Return 값: 없음

Code

solution.py

def makeRecord(name, deadline, number, priority):
    record = [name, deadline, number, priority]
    return record

def checkDeadlind(record, today):
    if (type(record[1]) != str):
        return False
    year = record[1][:4]
    month = record[1][4:6]
    day = record[1][6:]
    if (year != "2020"):
        return -1
    elif (int(month) not in range(1, 13)):
        return -2
    elif (int(day) not in range(1, 32)):
        return -3
    elif (int(today[4:6]) > int(month)):
        return -4
    elif (int(today[4:6]) == int(month) and int(today[6:]) > int(day)):
        return -4
    else:
        return True

def checkPriority(record):
    if(record[3] in [1, 2, 3]):
        return True
    else:
        return False

class ToDoList:
    ToDoList = []
    def addItem(self, newrecord):
        if(checkDeadlind(newrecord, "20200718") != True):
            return False
        elif(checkPriority(newrecord) == False):
            return False
        else:
            for i in range(len(self.ToDoList)):
                if (self.ToDoList[i][2] == newrecord[2]):
                    return False
            self.ToDoList.append(newrecord)
            return True

    def GetEarliestItem(self):
        earliest = self.ToDoList[0]
        for i in range(1, len(self.ToDoList)):
            if (int(self.ToDoList[i][1][4:]) < int(earliest[1][4:])):
                earliest = self.ToDoList[i]
            elif (int(self.ToDoList[i][1][4:]) == int(earliest[1][4:])):
                if(self.ToDoList[i][2] < earliest[2]):
                    earliest = self.ToDoList[i]
        return earliest
    
    def getItemByName(self, name):
        namelist = []
        for i in range(len(self.ToDoList)):
            namelist.append(self.ToDoList[i][0])
        
        if(name not in namelist):
            return False

        temp = []
        for i in range(len(self.ToDoList)):
            if (self.ToDoList[i][0] == name):
                temp.append(self.ToDoList[i])
        
        todo = []
        early_month = int(temp[0][1][4:6])
        early_day = int(temp[0][1][6:])
        early_index = 0
        while(temp != []):
            for i in range(1, len(temp)):
                compare_month = int(temp[i][1][4:6])
                compare_day = int(temp[i][1][6:])
                if(early_month > compare_month):
                    early_month = compare_month
                    early_day = compare_day
                    early_index = i
                elif(early_month == compare_month):
                    if(early_day > compare_day):
                        early_month = compare_month
                        early_day = compare_day
                        early_index = i
                    else:
                        if(temp[early_index][3] > temp[i][3]):
                            early_month = compare_month
                            early_day = compare_day
                            early_index = i
            todo.append(temp[early_index])
            del temp[early_index]
        return todo

    def getItemsByEDF(self, option):
        copy = self.ToDoList[:]
        result = []

        if(option == True):
            while(copy != []):
                early_month = int(copy[0][1][4:6])
                early_day = int(copy[0][1][6:])
                early_index = 0
                for i in range(1, len(copy)):
                    compare_month = int(copy[i][1][4:6])
                    compare_day = int(copy[i][1][6:])
                    if(early_month > compare_month):
                        early_month = compare_month
                        early_day = compare_day
                        early_index = i
                    elif(early_month == compare_month):
                        if(early_day > compare_day):
                            early_month = compare_month
                            early_day = compare_day
                            early_index = i
                        elif(early_day == compare_day):
                            if(copy[early_index][3] > copy[i][3]):
                                early_month = compare_month
                                early_day = compare_day
                                early_index = i
                result.append(copy[early_index])
                del copy[early_index]
            return result
        
        else:
            while(copy != []):
                latest_month = int(copy[0][1][4:6])
                latest_day = int(copy[0][1][6:])
                latest_index = 0
                for i in range(1, len(copy)):
                    compare_month = int(copy[i][1][4:6])
                    compare_day = int(copy[i][1][6:])
                    if(latest_month < compare_month):
                        latest_month = compare_month
                        latest_day = compare_day
                        latest_index = i
                    elif(latest_month == compare_month):
                        if(latest_day < compare_day):
                            latest_month = compare_month
                            latest_day = compare_day
                            latest_index = i
                        elif(latest_day == compare_day):
                            if(copy[latest_index][3] < copy[i][3]):
                                latest_month = compare_month
                                latest_day = compare_day
                                latest_index = i
                result.append(copy[latest_index])
                del copy[latest_index]
            return result

    def getItemDeadline(self, number):
        for i in range(len(self.ToDoList)):
            if(self.ToDoList[i][2] == number):
                return self.ToDoList[i][1]
        return False

    def deferDeadline(self, number, delay):
        if(delay >= 14):
            return False
        for i in range(len(self.ToDoList)):
            if(self.ToDoList[i][2] == number):
                year = int(self.ToDoList[i][1][:4])
                month = int(self.ToDoList[i][1][4:6])
                day = int(self.ToDoList[i][1][6:])
                day = day + delay
                if(day > 31):
                    day -= 31
                    month = month + 1
                    if(month > 12):
                        month -= 12
                        year = year + 1
                if(month < 10):
                    new_month = "0" + str(month)
                else:
                    new_month = str(month)
                if(day < 10):
                    new_day = "0" + str(day)
                else:
                    new_day = str(day)
                new_deadline = str(year) + new_month + new_day
                self.ToDoList[i][2] = new_deadline
                return new_deadline
                
    def writeFile(self):
        sortedToDoList = self.getItemsByEDF(True)
        outfile = open('output.csv', 'w')
        for i in range(len(self.ToDoList)):
            line = "{1}, {2}, {3}, {4}".format(sortedToDoList[i][0], sortedToDoList[i][1], sortedToDoList[i][2], sortedToDoList[i][3])
            outfile.write(line)

test.py

from solution import *

if __name__ == "__main__":

    ### General Fuction ###
    print ("### General Function ###")
    print()

    # makeRecord 
    print("makeRecord function")
    record = makeRecord("홍길동", "20200718", "A001", 1)
    print(record)
    print()

    # checkDeadline
    print("checkDeadline function")
    record[1] = 20200718
    print("Deadline is 20200718 and today is \'20200718\'")
    print(checkDeadlind(record, "20200718"))
    print("Deadline is \'20190718\' and today is \'20200718\'")
    record[1] = "20190718"
    print(checkDeadlind(record, "20200718"))
    print("Deadline is \'20201318\' and today is \'20200718\'")
    record[1] = "20201318"
    print(checkDeadlind(record, "20200718"))
    print("Deadline is \'20200732\' and today is \'20200718\'")
    record[1] = "20200732"
    print(checkDeadlind(record, "20200718"))
    print("Deadline is \'20200718\' and today is \'20200719\'")
    record[1] = "20200718"
    print(checkDeadlind(record, "20200719"))
    print("Deadline is \'20200719\' and today is \'20200719\'")
    record[1] = "20200719"
    print(checkDeadlind(record, "20200719"))
    print()

    # checkPriority
    print("checkPriority function")
    print("Priority is 1")
    record[3] = 1
    print(checkPriority(record))
    print("Priority is 2")
    record[3] = 2
    print(checkPriority(record))
    print("Priority is 3")
    record[3] = 3
    print(checkPriority(record))
    print("Priority is 4")
    record[3] = 4
    print(checkPriority(record))
    print()
    print()
    print()



    ### ToDoList Class ###
    todo = ToDoList()
    print ("### ToDoList Class ###")
    print()

    # addItem method
    print("addItem method")
    print("After inserting [\"홍길동\", \"20200718\", \"A001\", 1]")
    print("Success?", todo.addItem(["홍길동", "20200718", "A001", 1]))
    print("ToDoList:", ToDoList.ToDoList)
    print("After inserting [\"홍길동\", 20200718, \"A001\", 1]")
    print("Success?", todo.addItem(["홍길동", 20200718, "A001", 1]))
    print("ToDoList:", ToDoList.ToDoList)
    print("After inserting [\"홍길동\", \"20200718\", \"A001\", 4]")
    print("Success?", todo.addItem(["홍길동", "20200718", "A001", 4]))
    print("ToDoList:", ToDoList.ToDoList)
    print("After inserting [\"홍길동\", \"20200718\", \"A001\", 1]")
    print("Success?", todo.addItem(["홍길동", "20200718", "A001", 1]))
    print("ToDoList:", ToDoList.ToDoList)
    print()

    ## getEarliestItem method
    print("getEarliestItem method")
    todo.addItem(["이몽룡", "20200731", "A002", 2])
    todo.addItem(["성춘향", "20201231", "A003", 3])
    todo.addItem(["전우치", "20200731", "A004", 1])
    print("ToDoList:", ToDoList.ToDoList[0])
    print("         ", ToDoList.ToDoList[1])
    print("         ", ToDoList.ToDoList[2])
    print("         ", ToDoList.ToDoList[3])
    print("Earliest record:", todo.GetEarliestItem())
    print()

    # getItemByName method
    print("getItemByName method")
    todo.addItem(["이몽룡", "20200801", "A005", 2])
    print("ToDoList:", ToDoList.ToDoList[0])
    print("         ", ToDoList.ToDoList[1])
    print("         ", ToDoList.ToDoList[2])
    print("         ", ToDoList.ToDoList[3])
    print("         ", ToDoList.ToDoList[4])
    print("흥부's record:", todo.getItemByName("흥부"))
    print("이몽룡's record:", todo.getItemByName("이몽룡"))
    todo.ToDoList[4][1] = "20200731"
    print("ToDoList:", ToDoList.ToDoList[0])
    print("         ", ToDoList.ToDoList[1])
    print("         ", ToDoList.ToDoList[2])
    print("         ", ToDoList.ToDoList[3])
    print("         ", ToDoList.ToDoList[4])
    print("흥부's record:", todo.getItemByName("흥부"))
    print("이몽룡's record:", todo.getItemByName("이몽룡"))
    print()

    # getItemNyEDF method
    print("getItemByEDF method")
    print("ToDoList with option true") 
    print(todo.getItemsByEDF(True))
    print("ToDoList with option false")
    print(todo.getItemsByEDF(False))
    print()

    # getItemDeadline method
    print("getItemDeadline method")
    print("get \'A001\' deadline:", todo.getItemDeadline("A001"))
    print("getItemDeadline method")
    print("get \'A009\' deadline:", todo.getItemDeadline("A009"))
    print()
    
    # deferDeadline method
    print("deferDeadline method")
    print("Before delay:", todo.getItemDeadline("A001"))
    print("After 15 days delay:", todo.deferDeadline("A001", 15))
    print("Before delay:", todo.getItemDeadline("A001"))
    print("After 13 days delay:", todo.deferDeadline("A001", 13))
    print("Before delay:", todo.getItemDeadline("A004"))
    print("After 13 days delay:", todo.deferDeadline("A004", 13))
    print()

0개의 댓글