[Tutor] Poor style to use list as "array"?
Angus Rodgers
angusr at bigfoot.com
Mon Jul 6 02:02:10 CEST 2009
On Sun, 5 Jul 2009 18:49:32 -0400, Kent Johnson wrote:
>On Sun, Jul 5, 2009 at 2:48 PM, Angus Rodgers<angusr at bigfoot.com> wrote:
>
>> for i in range(LEN - 1):
>> (count[i], amnt) = divmod(amnt, value[i])
Incidentally, I forgot to quote the next line:
count[-1] = m
Of course, this is much better incorporated into the loop, thus:
for i in range(LEN):
(count[i], amnt) = divmod(amnt, value[i])
and this lends itself to being rewritten in terms of some other
kind of iteration (as below).
>How about this:
>counts = []
>for val in value:
> count, amnt = divmod(amnt, val)
> counts.append(count)
I like that very much, because it is in the nature of the problem
that the numbers in the list 'value' are all distinct, and so can
be used as keys. However, as this remark suggests, I think I am
going to need 'count' to be a dictionary, rather than a list, and
the same goes for 'denom', and 'plural' (although this should be
keyed by the strings in 'denom', and we don't need the 'None's).
So it looks like we should have something like:
plural = {'penny':'pennies'}
counts = {}
for val in value:
(count, amnt) = divmod(amnt, val)
counts[val] = count
and, later in the program, something like this (comments stripped
for brevity, and one new comment added):
for val in value:
amnt = counts[val]
name = denom[val]
if amnt:
to_print -= 1
if printed:
if to_print:
buff += ", "
else:
buff += " and "
printed += 1
if amnt > 1:
# This should become a function
if name in plural:
name = plural[name]
else:
name += 's'
buff += "%d %s" % (amnt, name)
I haven't run this, but I'll try rewriting the program tomorrow.
It looks like there's nothing to it.
I'm much happier now, thanks!
--
Angus Rodgers
More information about the Tutor
mailing list