Functional Python Programming

(Wang) #1

Additional Tuple Techniques


This function relies on two other functions. They can be declared within the body of
rerank(). We'll show them separately. The following is the ranker, which accepts an
iterable, a base rank number, a collection of values with the same rank, and a key:


def ranker(sorted_iter, base, same_rank_seq, key):


"""Rank values from a sorted_iter using a base rank value.


If the next value's key matches same_rank_seq, accumulate those.


If the next value's key is different, accumulate same rank values


and start accumulating a new sequence.


"""


try:


value= next(sorted_iter)


except StopIteration:


dups= len(same_rank_seq)


yield from yield_sequence((base+1+base+dups)/2,
iter(same_rank_seq))


return


if key(value.raw) == key(same_rank_seq[0].raw):


yield from ranker(sorted_iter, base, same_rank_seq+[value],
key)


else:


dups= len(same_rank_seq)


yield from yield_sequence( (base+1+base+dups)/2,
iter(same_rank_seq))


yield from ranker(sorted_iter, base+dups, [value], key)


We've extracted the next item from the iterable collection of sorted values. If this
fails, there is no next item, and we need to emit the final collection of equal-valued
items in the same_rank_seq sequence. If this works, then we need to use the key()
function to see whether the next item, which is a value, has the same key as the
collection of equal-ranked items. If the key is the same, the overall value is defined
recursively; the reranking is the rest of the sorted items, the same base value for the
rank, a larger collection of same_rank items, and the same key() function.


If the next item's key doesn't match the sequence of equal-valued items, the result
is a sequence of equal-valued items. This will be followed by the reranking of the rest
of the sorted items, a base value incremented by the number of equal-valued items,
a fresh list of equal-rank items with just the new value, and the same key
extraction function.

Free download pdf