Skip to content

Instantly share code, notes, and snippets.

@airportyh
Last active December 11, 2017 14:40
Show Gist options
  • Select an option

  • Save airportyh/c0d116b21d1291769d458c9aba07c5b6 to your computer and use it in GitHub Desktop.

Select an option

Save airportyh/c0d116b21d1291769d458c9aba07c5b6 to your computer and use it in GitHub Desktop.

More Exercises for Lesson 2.5

Scores

The judges gave these scores:

scores = [7, 8, 9, 10, 5, 6, 7, 3, 4]

Write programs to:

  1. Print each score. (loop counter pattern)
  2. Print each score doubled. (loop counter pattern)
  3. Print all the scores in this list that are greater than 5. (loop and filter)
  4. Print all the scores in this list that are odd. (loop and filter)
  5. Print the total of the scores in this list. (accumulator pattern)
  6. Print the total of all the scores that are greater than 5. (accumulator + filter pattern)
  7. Print the total of all the scores that are odd. (accumulator + filter pattern)
  8. Print the count of the number of scores in the list that are greater than 5. (accumulator + filter pattern)
  9. Print the count of the number of scores in the list that are odd. (accumulator + filter pattern)

Bonus Challenges

  1. Print the average score.
  2. Print the largest score. (Hint: accumulator pattern with an if statement)
  3. Print the smallest score. (You can assume a score cannot be larger than 10.)
  4. Print the total score minus the largest and the smallest score.
  5. Print the average score minus the largest and smallest score.

Patterns in Lesson 2.5

This lesson covered a number of patterns (and combinations of them) that involve lists.

Loop and Counter Pattern

numbers = [1, 5, 2, 3, 4]
i = 0
while i < len(numbers):
  number = numbers[i]
  print("The %d-th number is %d" % (i, number))
  i = i + 1

(Loop and) Filter Pattern

numbers = [1, 5, 2, 3, 4]
i = 0
while i < len(numbers):
  number = numbers[i]
  if number % 2 == 0:
    print("%d is an even number." % (number))
  i = i + 1

Accumulator Pattern

numbers = [3, 6, 1, 4, 2, 5]
total = 0
i = 0
while i < len(numbers):
  number = numbers[i]
  total = total + number
  i = i + 1

Accumulator + Filter Pattern

numbers = [3, 6, 1, 4, 2, 5]
total = 0
i = 0
while i < len(numbers):
  number = numbers[i]
  if number % 2 == 0:
    total = total + number
  i = i + 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment