else:
return reverse(list[1:]) + list[:1] # add front item on the end
def ireverse(list):
res = list[:0] # empty, of same type
for i in range(len(list)):
res = list[i:i+1] + res # add each item to front
return res
The combination of the changes allows the new functions to work on any sequence,
and return a new sequence of the same type as the sequence passed in. If we pass in a
string, we get a new string as the result. In fact, they reverse any sequence object that
responds to slicing, concatenation, and len—even instances of Python classes and C
types. In other words, they can reverse any object that has sequence interface protocols.
Here they are working on lists, strings, and tuples:
>>> from rev2 import *
>>> reverse([1, 2, 3]), ireverse([1, 2, 3])
([3, 2, 1], [3, 2, 1])
>>> reverse("spam"), ireverse("spam")
('maps', 'maps')
>>> reverse((1.2, 2.3, 3.4)), ireverse((1.2, 2.3, 3.4))
((3.4, 2.3, 1.2), (3.4, 2.3, 1.2))
Implementing Sorts
Another staple of many systems is sorting: ordering items in a collection according to
some constraint. The script in Example 18-25 defines a simple sort routine in Python,
which orders a list of objects on a field. Because Python indexing is generic, the field
can be an index or a key—this function can sort lists of either sequences or mappings.
Example 18-25. PP4E\Dstruct\Classics\sort1.py
def sort(list, field):
res = [] # always returns a list
for x in list:
i = 0
for y in res:
if x[field] <= y[field]: break # list node goes here?
i += 1
res[i:i] = [x] # insert in result slot
return res
if name == 'main':
table = [ {'name':'john', 'age':25}, {'name':'doe', 'age':32} ]
print(sort(table, 'name'))
print(sort(table, 'age'))
table = [ ('john', 25), ('doe', 32) ]
print(sort(table, 0))
print(sort(table, 1))
Reversing and Sorting Sequences| 1399