NotesWhat is notes.io?

Notes brand slogan

Notes - notes.io

import os
__author__ = 'student'

'''

IMPORTANT NOTE: Do NOT change any of the function names or their signatures (the parameters they take).
Your functions must behave exactly as described. Please check for correctness by running DocTests
included in function headers.

Manage a calendar database.

A calendar is a dictionary keyed by date ("YYYY-MM-DD") with value being a list of
strings, the events on the specified date.

Example:
calendar["2015-10-12"] # is a list of events on "2015-10-12"

calendar["2015-10-12"]==["Eye doctor", "lunch with sid", "dinner with jane"]
'''

# ---------------------------------------------------------------------------------------------------------------------
# Implementation of calendar commands
# ---------------------------------------------------------------------------------------------------------------------

def command_help():
'''
Print out help for the system. That is...
:return: a string indicating any errors, "" for no errors
'''

help = """
Help for Calendar. The calendar commands are

add DATE DETAILS add the event DETAILS at the specified DATE
show show all events in the claendar
delete DATE NUMBER delete the specified event (by NUMBER) from the calendar
quit quit this program
help display this help message

Examples: user input follows command:

command: add 2015-10-12 dinner with jane
added

command: show
2015-10-12:
0: Eye doctor
1: lunch with sid
2: dinner with jane
2015-10-29:
0: Change oil in blue car
1: Fix tree near front walkway
2: Get salad stuff, leuttice, red peppers, green peppers
2015-11-06:
0: Sid's birthday

command: delete 2015-10-29 2
deleted

A DATE has the form YYYY-MM-DD, for example
2015-12-21
2016-01-02

Event DETAILS consist of alphabetic characters, not tabs or newlines allowed.
"""
print(help)
return ""


def command_add(date, event_details, calendar):
'''
Add event_details to the list at calendar[date]
Create date if it was not there

:param date: A string date formatted as "YYYY-MM-DD"
:param event_details: A string describing the event
:param calendars: The calendars database
:return: a string indicating any errors, "" for no errors

>>> calendar = {}
>>> command_add("2015-10-20", "Python class", calendar)
''
>>> calendar == {'2015-10-20': ['Python class']}
True
>>> command_add("2015-11-01", "CSC108 test 2", calendar)
''
>>> calendar == {'2015-11-01': ['CSC108 test 2'], '2015-10-20': ['Python class']}
True
>>> command_add("2015-11-01", "go out with friends after test", calendar)
''
>>> calendar == {'2015-11-01': ['CSC108 test 2', 'go out with friends after test'], '2015-10-20': ['Python class']}
True
>>>

'''

# YOUR CODE GOES HERE
if date in calendar:
if event_details not in calendar[date]:
calendar[date].append(event_details)
else:
calendar[date] = [event_details]

return("")

def command_show(calendar):
'''
Print the list of events for calendar sorted in increasing date order
:param calendar: the database of events
:return: a string indicating any errors, "" for no errors

Example:
>>> calendar = {}
>>> command_add("2015-10-12", "Eye doctor", calendar)
''
>>> command_add("2015-10-12", "lunch with sid", calendar)
''
>>> command_add("2015-10-29", "Change oil in blue car", calendar)
''
>>> command_add("2015-10-12", "dinner with Jane", calendar)
''
>>> command_add("2015-10-29", "Fix tree near front walkway", calendar)
''
>>> command_add("2015-10-29", "Get salad stuff", calendar)
''
>>> command_add("2015-11-06", "Sid's birthday", calendar)
''
>>> command_show(calendar)
2015-10-12:
0: Eye doctor
1: lunch with sid
2: dinner with Jane
2015-10-29:
0: Change oil in blue car
1: Fix tree near front walkway
2: Get salad stuff
2015-11-06:
0: Sid's birthday
''
'''
# Hint: Don't use t (the tab character) to indent, or DocTest will fail in the above testcase.
# Put 4 spaces before the date, 8 spaces before each item.



# YOUR CODE GOES HERE

for date in sorted(calendar):
print(" "+ date+":")
for event_details in calendar[date]:
print(" "+ str(calendar[date].index(event_details))+ ": " +event_details)

return("")


def command_delete(date, entry_number, calendar):
'''
Delete the entry at calendar[date][entry_number]
If calendar[date] is empty, remove this date from the calendar.

:param date: A string date formatted as "YYYY-MM-DD"
:param entry_number: An integer indicating the entry in calendar[date] to delete
:param calendar: The calendars database
:return: a string indicating any errors, "" for no errors

Example:

>>> calendar = {}
>>> command_add("2015-10-20", "Python class", calendar)
''
>>> calendar == {'2015-10-20': ['Python class']}
True
>>> command_add("2015-11-01", "CSC108 test 2", calendar)
''
>>> calendar == {'2015-11-01': ['CSC108 test 2'], '2015-10-20': ['Python class']}
True
>>> command_add("2015-11-01", "go out with friends after test", calendar)
''
>>> calendar == {'2015-11-01': ['CSC108 test 2', 'go out with friends after test'], '2015-10-20': ['Python class']}
True
>>> command_show(calendar)
2015-10-20:
0: Python class
2015-11-01:
0: CSC108 test 2
1: go out with friends after test
''

>>> command_delete("2015-01-01", 1, calendar)
'2015-01-01 is not a date in the calendar'
>>> command_delete("2015-10-20", 3, calendar)
'there is no entry 3 on date 2015-10-20 in the calendar'
>>> command_delete("2015-10-20", 0, calendar)
''
>>> calendar == {'2015-11-01': ['CSC108 test 2', 'go out with friends after test']}
True
>>> command_delete("2015-11-01", 0, calendar)
''
>>> calendar == {'2015-11-01': ['go out with friends after test']}
True
>>> command_delete("2015-11-01", 0, calendar)
''
>>> calendar == {}
True

'''


# YOUR CODE GOES HERE
if date not in calendar:
return(date+' is not a date in the calendar')
elif date in calendar:
if int(entry_number) >= len(calendar[date]):
return('there is no entry '+ str(entry_number) + ' on date '+ date+' in the calendar')
else:
calendar[date].pop(int(entry_number))
if calendar[date]==[]:
calendar.pop(date)


return('')



# ---------------------------------------------------------------------------------------------------------------------
# Functions dealing with calendar persistence
# ---------------------------------------------------------------------------------------------------------------------

'''
The calendar is read and written to disk.

...

date_i is "YYYY-MM-DD"'
description can not have tab or new line characters in them.

'''

def save_calendar(calendar):
'''
Save calendar to 'calendar.txt', overwriting it if it already exists.

The format of calendar.txt is the following:

date_1:description_1tdescription_2t...tdescription_nn
date_2:description_1tdescription_2t...tdescription_nn
date_3:description_1tdescription_2t...tdescription_nn
date_4:description_1tdescription_2t...tdescription_nn
date_5:description_1tdescription_2t...tdescription_nn

Example: The following calendar...

2015-10-20:
0: Python class
2015-11-01:
0: CSC108 test 2
1: go out with friends after test

appears in calendar.txt as ...

2015-10-20:Python class
2015-11-01:CSC108 test 2 go out with friends after test

^^^^ This is a t, (tab) character.


:param calendar:
:return: True/False, depending on whether the calendar was saved.
'''
# YOUR CODE GOES HERE
output_file=open('calendar', 'w')

for date in sorted(calendar):
output_file.write(str(date) +":")
for event_details in calendar[date]:
if calendar[date].index(event_details)==(len(calendar[date])-1):
output_file.write(event_details+"n")
else:
output_file.write(event_details+"t")
output_file.close()

if os.path.exists('calendar'):
return True
else:
return False

def load_calendar():
'''
Load calendar from 'calendar.txt'. If calendar.txt does not exist,
create and return an empty calendar. For the format of calendar.txt
see save_calendar() above.

:return: calendar, or False, if calendar could not be loaded from disk.

'''

# YOUR CODE GOES HERE
calendar={}
check=False


if os.path.exists('calendar'):
input_file = open("calendar","r")
for line in input_file:
if (':' in line): #checks for (':')
line = line.rstrip()
line = line.split(":")
date = line[0]
if(is_calendar_date(date)): #checks if the date is formated correctly
event = line[1].split('t')
for i in range(0,len(event)):
command_add(date,event[i],calendar)
else:check=True #checks if the date is formated correctly
else:check=True #checks for (':')
input_file.close()
else:
input_file=open("calendar","w")
input_file.close()

if check:
return False
else:
return (calendar)



# ---------------------------------------------------------------------------------------------------------------------
# Functions dealing with parsing commands
# ---------------------------------------------------------------------------------------------------------------------

def is_command(command):
'''
Return whether command is indeed a command, that is, one of
"add", "delete", "quit", "help", "show"
:param command: string
:return: True if command is one of ["add", "delete", "quit", "help", "show"], false otherwise
Example:
>>> is_command("add")
True
>>> is_command(" add ")
False
>>> is_command("List")
False

'''
command1=['add','delete','quit','help','show']
if command in command1:
return(True)
else:
return(False)

# YOUR CODE GOES HERE
def is_calendar_date(date):
'''
Return whether date looks like a calendar date
:param date: a string
:return: True, if date has the form "YYYY-MM-DD" and False otherwise

Example:

>>> is_calendar_date("15-10-10") # invalid year
False
>>> is_calendar_date("2015-10-15")
True
>>> is_calendar_date("2015-5-10") # invalid month
False
>>> is_calendar_date("2015-15-10") # invalid month
False
>>> is_calendar_date("2015-05-10")
True
>>> is_calendar_date("2015-10-55") # invalid day
False
>>> is_calendar_date("2015-55") # invalid format
False
>>> is_calendar_date("jane-is-gg") # YYYY, MM, DD should all be digits
False

Note: This does not validate days of the month, or leap year dates.

>>> is_calendar_date("2015-04-31") # True even though April has only 30 days.
True

'''
# Algorithm: Check length, then pull pieces apart and check them. Use only basic string
# manipulation, comparisons, and type conversion. Please do not use any powerful date functions
# you may find in python libraries.
# 2015-10-12
# 0123456789

# YOUR CODE GOES HERE
if len(date)==10:
dates=date.split("-")
if (len(dates[0])==4 and is_natural_number(dates[0])) and (len(dates[1])==2 and is_natural_number(dates[1])) and (len(dates[2])==2 and is_natural_number(dates[2])):
if ((int(dates[1]))<=12) and ((int(dates[2]))<=31):
return True
else:return False
else:return False
else:
return False


def is_natural_number(str):
'''
Return whether str is a string representation of a natural number,
that is, 0,1,2,3,...,23,24,...1023, 1024, ...
In CS, 0 is a natural number
:param str: string
:return: True if num is a string consisting of only digits. False otherwise.
Example:

>>> is_natural_number("0")
True
>>> is_natural_number("05")
True
>>> is_natural_number("2015")
True
>>> is_natural_number("9 3")
False
>>> is_natural_number("sid")
False
>>> is_natural_number("2,192,134")
False

'''
# Algorithm:
# Check that the string has length > 0
# Check that all characters are in ["0123456789"]

# YOUR CODE GOES HERE

check=True
if len(str)>0:
for c in str:
if c not in "0123456789":
check=False
else:
return False

return check



def parse_command(line):
'''
Parse command and arguments from the line. Return a list [command, arg1, arg2, ...]
Return ["error", ERROR_DETAILS] if the command is not valid. Return ["help"] otherwise.
The valid commands are

1) add DATE DETAILS
2) show
3) delete DATE NUMBER
4) quit
5) help

:param line: a string command
:return: A list consiting of [command, arg1, arg2, ...]. Return ["error", ERROR_DETAILS], if
line can not be parsed.

Example:
>>> parse_command("add 2015-10-21 budget meeting")
['add', '2015-10-21', 'budget meeting']
>>> parse_command("")
['help']
>>> parse_command("not a command")
['help']
>>> parse_command("help")
['help']
>>> parse_command("add")
['error', 'add DATE DETAILS']
>>> parse_command("add 2015-10-22")
['error', 'add DATE DETAILS']
>>> parse_command("add 2015-10-22 Tims with Sally.")
['add', '2015-10-22', 'Tims with Sally.']
>>> parse_command("add 2015-10-35 Tims with Sally.")
['error', 'not a valid calendar date']
>>> parse_command("show")
['show']
>>> parse_command("show calendar")
['error', 'show']
>>> parse_command("delete")
['error', 'delete DATE NUMBER']
>>> parse_command("delete 15-10-22")
['error', 'delete DATE NUMBER']
>>> parse_command("delete 15-10-22 1")
['error', 'not a valid calendar date']
>>> parse_command("delete 2015-10-22 3,14")
['error', 'not a valid event index']
>>> parse_command("delete 2015-10-22 314")
['delete', '2015-10-22', '314']
>>> parse_command("quit")
['quit']

'''
# HINT: You can first split, then join back the parts of the final argument.


# YOUR CODE GOES HERE
args=line.split()
if args==[]:
args=['help']
return args

elif args[0] in ['help', 'quit', 'show']:
if len(args)>1:
args=['error', args[0]]
return args
else:
return args

elif args[0]=="add":
if len(args)>2 and is_calendar_date(args[1]):
args[2]=" ".join(args[2:])
return args[:3]
elif len(args)<3:
args=['error', 'add DATE DETAILS']
return args
else:
args=['error', 'not a valid calendar date']
return args

elif args[0]=="delete" :
if len(args)==3 and is_natural_number(args[2]) and is_calendar_date(args[1]):
return args
elif len(args)<3:
args=['error', 'delete DATE NUMBER']
return args
elif is_calendar_date(args[1])==False:
args=['error', 'not a valid calendar date']
return args
else:
args=['error', 'not a valid event index']
return args
else:
args=['help']
return args


# ---------------------------------------------------------------------------------------------------------------------
# Functions dealing with the user. This is the calendar application.
# ---------------------------------------------------------------------------------------------------------------------

def user_interface():
'''
Load calendar.txt and then interact with the user. The user interface
operates as follows, the text after command: is the command entered by the user.

calendar loaded
command: add 2015-10-21 budget meeting
added
command: add 2015-10-22 go to the gym
added
command: add 2015-10-23 go to the gym
added
command: add 2015-11-01 Make sure to submit csc108 assignment 2
added
command: add 2015-12-02 Make sure to submit csc108 assignment 3
added
command: add 2015-11-06 Term test 2
added
command: add 2015-10-29 Get salad stuff, leuttice, red peppers, green peppers
added
command: add 2015-11-06 Sid's birthday
added
command: show
2015-10-21:
0: budget meeting
2015-10-22:
0: go to the gym
2015-10-23:
0: go to the gym
2015-10-29:
0: Get salad stuff, leuttice, red peppers, green peppers
2015-11-01:
0: Make sure to submit csc108 assignment 2
2015-11-06:
0: Term test 2
1: Sid's birthday
2015-12-02:
0: Make sure to submit csc108 assignment 3
command: delete 2015-10-29 0
deleted
command: delete 2015-12-03 0
2015-12-03 is not a date in the calendar
command: delete 2015-12-02 0
deleted
command: show
2015-10-21:
0: budget meeting
2015-10-22:
0: go to the gym
2015-10-23:
0: go to the gym
2015-11-01:
0: Make sure to submit csc108 assignment 2
2015-11-06:
0: Term test 2
1: Sid's birthday
command: quit
calendar saved

:return: None
'''

# YOUR CODE GOES HERE
if load_calendar()!=False:
print('calendar loaded')
n=input("command:")
calendar=load_calendar()


while (n!='quit'):
action=parse_command(n)
if action[0]=='add':
command_add(action[1],action[2],calendar)
print('added')
elif action[0]=='delete':
if (command_delete(action[1],action[2],calendar)==''):
command_delete(action[1],action[2],calendar)
print('deleted')
else:
print(command_delete(action[1],action[2],calendar))
elif action[0]=='show':
command_show(calendar)
else:
print(action)
n=input("command:")

if save_calendar(calendar):
print('calendar saved')
else:
print('not saved')
else:print('non calendar input')




if __name__ == "__main__":
user_interface()
     
 
what is notes.io
 

Notes.io is a web-based application for taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000 notes created and continuing...

With notes.io;

  • * You can take a note from anywhere and any device with internet connection.
  • * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
  • * You can quickly share your contents without website, blog and e-mail.
  • * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
  • * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.

Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.

Easy: Notes.io doesn’t require installation. Just write and share note!

Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )

Free: Notes.io works for 12 years and has been free since the day it was started.


You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;


Email: [email protected]

Twitter: http://twitter.com/notesio

Instagram: http://instagram.com/notes.io

Facebook: http://facebook.com/notesio



Regards;
Notes.io Team

     
 
Shortened Note Link
 
 
Looding Image
 
     
 
Long File
 
 

For written notes was greater than 18KB Unable to shorten.

To be smaller than 18KB, please organize your notes, or sign in.