Programming Exercises in Python

Multiples of Three

Write a function multiples_of_three(A) that takes an array \(A\) of integers and prints the count of all the elements of \(A\) that are multiples of three.

Examples:

>>> multiples_of_three([34, 31, 45, 5, 38, 19, 19, 26, 25, 19, 39, 40])
2
>>> multiples_of_three([7, 2, 0])
0

Maximal Difference

Write a function max_diff(A) that takes an array \(A\) of numbers and prints the maximal difference between any two elements of the array. If the array is empty, the function should not print anything.

Examples:

>>> max_diff([32, 6, 4, 14, 50, 12, 23, 25, 46, 32, 40, 8])
46
>>> max_diff([7])
0
>>> max_diff([])

Isolated Elements

Write a function isolated_elements(A) that prints all the isolated elements of a given array \(A\). An element of \(A\) is not isolated when it has an equal element adjacent to it. Otherwise, the element is isolated.

Examples:

>>> isolated_elements([-1,1,1,1,0,7,8,7,5,5,1,1,4,1])
-1
0
7
8
7
4
1
>>> isolated_elements([9,9])
>>> isolated_elements([9])
9

Horizontal Histogram

Write a function histogram(A) that takes an array of non-negative integers, and prints a histogram corresponding to those numbers. In this histogram, each number \(N\) is represented by a line of \(N\) characters #. For example, with this input:

Example:

>>> histogram([10, 15, 7, 9, 1, 3])
##########
###############
#######
#########
#
###
>>> histogram([])
>>> histogram([1,2,4,0,8,16])
#
##
####

########
################

Vertical Histogram

Write a function vertical_histogram(A) that takes an array of integers, and prints a vertical histogram corresponding to those values. In this histogram, each number \(N\) is represented by a column of \(N\) characters # starting from a base line of \(N\) dash characters - representing value 0. Positive numbers are represented by a column above zero while negative numbers are represented with a column below zero.

Example:

>>> vertical_histogram([7, 3, -2, 10, 5, -3, 3, 5, 8])
   #     
   #     
   #    #
#  #    #
#  #    #
#  ##  ##
#  ##  ##
## ## ###
## ## ###
## ## ###
---------
  #  #   
  #  #   
     #   

Compression of a Sequence

Write a function compress(A) that prints a “compressed” version of the \(A\) sequence. The compression is obtained by printing a sequence of three or more identical elements as \(X\) * \(N\), where \(X\) is the element and \(N\) is the number of consecutive copies of \(X\).

Example:

>>> compress([-1,1,1,1,7,7,7,7,5,5,1,1,4,1])
-1
1 * 3
7 * 4
5
5
1
1
4
1
>>> compress([])
>>> compress([1,2,2,3,3,3])
1
2
2
3 * 3