[Tutor] converting to Ascii from hex [writing a group()
function]
Danny Yoo
dyoo@hkn.eecs.berkeley.edu
Fri, 8 Feb 2002 01:26:52 -0800 (PST)
On Fri, 8 Feb 2002, Danny Yoo wrote:
> This looks good. If we want, we can write a few functions to tease out
> some of the functionality. A large part of the program appears to try
> grouping pairs of elements in the sequence. We can generalize the grouping
> by writing a function like this:
>
> ###
> def group(seq, n=2):
> """Given a sequence 'seq', returns a list that clumps up
> 'n' adjacent elements together. By default, n=2."""
> pieces = []
> for i in range(len(seq) / n):
> pieces.append(seq[i*n : (i+1)*n])
> return pieces
> ###
Hmmm... I should be careful about the division here, since Python is bound
to transition off to use true division, sooner or later. Here's another
version of the group() function:
###
def group(seq, n=2):
"""Given a sequence 'seq', returns a list that clumps up
'n' adjacent elements together. By default, n=2."""
pieces = []
for i in range(int(len(seq) / n)):
pieces.append(seq[i*n : (i+1)*n])
return pieces
###
There! This also makes explicit the fact that we do want to do a
truncation, so that group() always has groups that are 'n' elements long.
For example:
###
>>> group(['key1', 'value1', 'key2', 'value2', 'key3'])
[['key1', 'value1'], ['key2', 'value2']]
###
will make sure that we ignore any trailing pieces of a sequence when we're
doing a grouping.