[Tutor] Poor style to use list as "array"?

Angus Rodgers angusr at bigfoot.com
Sun Jul 5 20:48:37 CEST 2009


The problem this time is, given an amount of US currency in cents
(and less than a dollar), to print out a description of the coins
needed to represent it, using the smallest number of coins.  E.g.:

How many cents this time? 59
2 quarters, 1 nickel and 4 pennies.

How many cents this time? 55
2 quarters and 1 nickel.

How many cents this time? 75
3 quarters.

My program relaxes the restriction to amounts less than a dollar,
and initialises the necessary data structures as follows:

denom = ['dollar', 'quarter', 'dime', 'nickel', 'penny']
value = [100, 25, 10, 5, 1]
LEN = 5
plural = [None] * LEN
plural[-1] = 'pennies'
count = [None] * LEN   # Kludge

I use the list 'count' as a kind of array, so that e.g. count[-1]
is the number of pennies needed, count[2] is the number of dimes
needed, and so on.  Any initial values I might store as elements
of the list are never used, hence the use of 'None'. (The use of
'None' in the list 'plural' is much more defensible, I think, as
it is used to denote the formation of a regular plural by adding
's' to the name.) Instead, the actual values are assigned in a
'for' loop, as follows:

for i in range(LEN - 1):
    (count[i], amnt) = divmod(amnt, value[i])

This feels like a bit of a cheat, as if I am trying to program in
Python as if it were some other more familiar language.  Should I
have coded this differently?

The full source code is here, in case anyone wants to look at it
(but I'm not soliciting any more attention, as I've already been
given quite a lot of it, and fear being offered the comfy chair!):
<http://python.pastebin.com/d5e321ae0>   (retention: 1 day)

Could I have used dictionaries instead, with the denomination names
as keys?  Is it possible to guarantee a sequence in which the keys
of a dictionary are iterated through? (If not, I suppose I could
keep the list 'denom' as it is here, and iterate through it with
"for key in denom:", although this seems a bit redundant.)
-- 
Angus Rodgers


More information about the Tutor mailing list