Python - Functions with lists P51956


Statement
 

pdf   zip

html

In this problem you must implement several functions on lists in Python.

  1. Write a function myLength(L) that, given a list, returns its length.
  2. Write a function myMaximum(L) that, given a non-empty list, returns its maximum.
  3. Write a function average(L) that, given a non-empty list of numbers, returns its average.
  4. Write a function buildPalindrome(L) that, given a list, returns the palindrome that starts with the reverse of the list.
  5. Write a function remove(L1, L2) that, given a list L1 and a list L2, returns the list L1 after removing the occurrences of the elements in L2.
  6. Write a function flatten(L) that recursively flattens a list whose elements may also be lists of different levels. Hint: use recursion and the isinstance(x, list) built-in function.
  7. Write a function oddsNevens(L) that, given a list of integers, returns two lists, one with all the odd numbers and one with all the even numbers, in the same relative order than the original.
  8. Write a function primeDivisors(n) that returns the list of all prime divisors of a non-zero positive integer.

Scoring

Each function scores 12 points and the sample 4.

Sample session
>>> myLength([1,3,6,1])
4
>>> myMaximum([4,3,1,5,4,5,2])
5
>>> myMaximum(['josep', 'jordi', 'albert'])
josep
>>> average([1,2,3])
2.0
>>> buildPalindrome(['pa','amb','oli'])
['oli', 'amb', 'pa', 'pa', 'amb', 'oli']
>>> flatten([[2,6],[[8,1,4],[3,'uau']],[[],[1]],[[]]])
[2, 6, 8, 1, 4, 3, 'uau', 1]
>>> remove([1,4,5,3,4,5,1,2,7,4,2], [2,4])
[1, 5, 3, 5, 1, 7]
>>> oddsNevens([1,4,5,3,4,5,1,2,7,4,2])
([1, 5, 3, 5, 1, 7], [4, 4, 2, 4, 2])
>>> primeDivisors(255)
[3, 5, 17]
Information
Author
Jordi Petit
Language
English
Translator
Jordi Petit
Original language
Catalan
Other languages
Catalan
Official solutions
Python
User solutions
Python