This function is used by Section 24, “yearBrackets(): Display a bracketed list of
years worked” to find
sequences of years in a list.
# - - - c o u n t V a l u e s
def countValues(numberList):
'''Count the number of each value in numberList.
[ numberList is a list of ints order, possibly with some
duplicates ->
return a list of (value, count) pairs in ascending
order by value such that each single value is represented
as (value, 1) and each group of N duplicates is represented
as (value, N) ]
'''
#-- 1
# [ pairList := a new, empty list
# myList := a copy of numberList, sorted ]
pairList = []
myList = sorted(numberList)
In each pass through this loop, we work through myList, counting and removing the number of rows that
are equal to the first row. Then we add the value and the count
to pairList and repeat.
#-- 2
# [ pairList +:= (value, count) pairs representing contiguous
# groups of equal values in myList
# myList := empty ]
while len(myList) > 0:
#-- 2 body
# [ myList is a nonempty list ->
# myList := myList with all initial elements removed
# that have the same value
# pairList +:= a pair (myList[0], c) where c is the
# number of initial elements with the same value ]
first = myList.pop(0)
count = 1
while ( ( len(myList) > 0 ) and
( first == myList[0] ) ):
count += 1
myList.pop(0)
pairList.append ( (first, count) )
#-- 3
return pairList