# book example # book = { # 'name': 'Programming with Python 3', # 'pages': 157, # 'read': True # } bookshelf = [False] * 10 # = [False, False, False, False, False, False, False, False, False, False] # (0) this function will return False, if there is a book at specified "position" in bookshelf. If there is none, return True (True → there is no book, the space is free) # position = index (0 - 9) # this function is not graded, but is used in other functions def isFree(position): return not bool(bookshelf[position]) # (1) this function will add a book with "name", number of pages "pages" and wether the book was read "read" # if there already is a book at given "position", this function does nothing # use the function "isFree" def addBook(position, name, pages, read = False): if isFree(position): bookshelf[position] = { "name": name, "pages": pages, "read": read } # (2) returns False or index of the book with a given "name" def findBook(name): for book in bookshelf: if book: if book["name"] == name: return bookshelf.index(book) # (3) this function uses the "findBook" function and if there is a book with a given "name" in the "bookshelf", it changes its "read" value to True def readBook(name): if findBook(name): bookshelf[findBook(name)]["read"] = True # (4) this function removes all books that were read from the "bookshelf" (read == True) (replaces them with False) def removeReadBooks(): for book in bookshelf: if book: if book["read"]: bookshelf[bookshelf.index(book)] = False # (5) returns a list with names of books in the "bookshelf" def namesOfBooks(): names = [] for book in bookshelf: if book: names.append(book["name"]) return names # BONUS: returns the average number of pages of books in the "bookshelf" def averageNumberOfPages(): sum = 0 count = 0 for book in bookshelf: if book: sum += book["pages"] count += 1 return sum/float(count) # testing # 1 addBook(0, 'A Byte of python', 120, read = True) addBook(1, 'Automate the boring stuff with Python', 420) addBook(2, 'Python for Informatics', 500, read = True) addBook(3, 'Learning Geospatial Analysis with Python', 155) addBook(4, 'Python Geospatial Development', 211) addBook(5, 'Python for Data Analysis', 362, read = True) addBook(5, 'Programming Java', 874) print isFree(5) # False print isFree(6) # True # 2 print findBook('A Byte of python') # 0 print findBook('Python Geospatial Development') # 4 print findBook('Programming Java') # False # 3 readBook('A Byte of python') readBook('Automate the boring stuff with Python') readBook('Programming Java') # 4 removeReadBooks() print isFree(1) # True print isFree(3) # False # 5 print namesOfBooks() # ['Learning Geospatial Analysis with Python', 'Python Geospatial Development'] # BONUS print averageNumberOfPages() # 183 # HINT print bookshelf # [False, False, False, {'pages': 155, 'name': 'Learning Geospatial Analysis with Python', 'read': False}, {'pages': 211, 'name': 'Python Geospatial Development', 'read': False}, False, False, False, False, False]