6.2 - Page count
A school library wants to analyse the sizes of books in its collection.
The program should:
- Store the page counts of a set of library books in an array.
- Find and display the largest number of pages in the array.
- Count how many books have over 300 pages and display the result.
Using the problem description and design, implement the program.
The largest book has 500 pages. There are 4 books with more than 300 pages.
book_pages = [120, 340, 220, 340, 150, 500, 340]
| 1 | Find and display the largest page count | IN | book_pages |
| 2 | Count and display the number of books over 300 pages | IN | book_pages |
1.1 set max_pages to first element in pages
1.2 for each remaining element in pages do
1.3 if current element > max_pages then
1.4 set max_pages to current element
1.5 display “The largest book has” and max_pages
2.1 set count to 0
2.2 for each element in pages do
2.3 if element > 300 then
2.4 increase count by 1
2.5 display “There are” and count and “books with more than 300 pages”
# main program book_pages = [120, 340, 220, 340, 150, 500, 340] show_max(book_pages) count_over_300(book_pages)
def show_max(pages):
max_pages = pages[0]
for i in range(1, len(pages)):
if pages[i] > max_pages:
max_pages = pages[i]
print("The largest book has", max_pages, "pages.")
def count_over_300(pages):
count = 0
for i in range(len(pages)):
if pages[i] > 300:
count = count + 1
print("There are", count, "books with more than 300 pages.")
# main program
book_pages = [120, 340, 220, 340, 150, 500, 340]
show_max(book_pages)
count_over_300(book_pages)
def show_max(pages): # 'pages' is the parameter that receives the array
max_pages = pages[0]
for i in range(1, len(pages)):
if pages[i] > max_pages:
max_pages = pages[i]
print("The largest book has", max_pages, "pages.")
def count_over_300(pages): # 'pages' is the parameter that receives the array
count = 0
for i in range(len(pages)):
if pages[i] > 300:
count = count + 1
print("There are", count, "books with more than 300 pages.")
# main program
book_pages = [120, 340, 220, 340, 150, 500, 340]
show_max(book_pages) # 'book_pages' array is passed into the parameter 'pages'
count_over_300(book_pages) # 'book_pages' array is passed into the parameter 'pages'