Skip to content

Exercises

5.1 — Given the list nums = [5, 3, 9, 1, 7]. Write a program that prints its length, sum, max, min, and average. Then sort the list in ascending and descending order without losing the original order, and print the results.

5.2 — Write a program that reads numbers from the user until they enter an empty line, collecting them into a list. The program then prints the list, its total, and its average.

5.3 — Write a program that reads text from the user, splits the text it into words and prints the following:

  • the word count
  • the longest word
  • the list of words longer than 4 letters

5.4 — Write a program that reads a list of numbers from the user. Create a new list with the even numbers removed and then print both lists.

5.5 — Write a program stats.py that reads a list of numbers from the user. The program then calculates the count, sum, average, min, max and the median (sort then pick the middle, handling both even and odd lengths) and prints the results to the screen.

5.6 — Write a program dedupe.py that reads a list of numbers from the user and produces a new list without duplicates while preserving the original order. Print both lists to the screen.

5.7 — Write a program rotate.py that reads a list of numbers from the user and a rotation position k (an integer; must be less than the length of the list). The program then produces a new list from the input list rotated by k positions and prints both lists to the screen.

Examples:

  • [1,2,3,4] with k = 1 ⇒ [2,3, 4, 1]
  • [1,2,3,4] with k = 2 ⇒ [3,4,1,2]

5.8 — A perfect number is a number that is equal to the sum of its proper divisors (excluding the number itself). Write a program that reads a number from the user, finds its divisors and calculates their sum. The program then declares if the number is "perfect" or not.

Hints
  • 5.2 — check if the value returned by input() is empty and use break to end the loop
  • 5.4 — a list comprehension that filters on n % 2 != 0 would be perfect here
  • 5.5 — average and median are different. The median is the value literally in the middle after the list is sorted
  • 5.6 — build a new list, doing a membership check on each iteration before adding the number to the new list