[Tutor] Re: newbie looking for code suggestions

Thorsten Kampe thorsten@thorstenkampe.de
Sun, 22 Sep 2002 14:13:15 +0200


* Bob Roher
> Hi all.  I was wondering if anyone could look over the following code and give me any suggestions or criticisms?  I just started learning Python a few days ago, so I'm sure there's a lot that can
> be done to make it look and run better.

Please insert line breaks at about column 70 so your readers do not
have to scroll horizontally.

> #This program was written in response to following question:
> #How many numbers between 1 and 999999 have 21 as the total of
> #their digits?
> #For example: 902,550 is 9+0+2+5+5+0 = 21
> #After finding the answer, I wanted to expand it to find any total
> #in an integer range.

First you should separate the core code (algorithm) from the
input/output/error checking stuff.

The "total of their digits" is the "cross sum" of a number. I've
written three variations to demonstrate different techniques:

#v+
def cross_sum(integer):
    if integer:
        return integer % 10 + cross_sum(integer / 10)
    else:
        return 0

def cross_sum(integer):
    sum = 0
    while integer:
        sum += integer % 10
        integer /= 10
    return sum

def cross_sum(integer):
    sum = 0
    for digit in str(integer):
        sum += int(digit)
    return sum
#v-

The iterative version ("while") performs best.

Okay, so mathematically spoken, you want the size of a certain list
where each item is equivalent to the others by it's cross sum (sorry
Magnus). This is the code for the "equivalent lists":

#v+
def quotient_set(seq, func):
    """ partition seq into equivalence classes """
    quotient_set = {}
    for item in seq:
        quotient_set.setdefault(repr(func(item)),[]).append(item)
    return quotient_set
#v-

That's all:

>>> min_number, max_number, digit_total = 1, 999999, 21
>>> len(quotient_set(range(min_number, max_number+1), cross_sum)[str(digit_total)])
39962

cpu: 28.121, total: 29.832

> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
> <HTML><HEAD>
> <META http-equiv=Content-Type content="text/html; charset=iso-8859-1">
> <META content="MSHTML 6.00.2600.0" name=GENERATOR>
> <STYLE></STYLE>
> </HEAD>
> <BODY bgColor=#ffffff>
> <DIV><FONT face=Arial size=2>Hi all.&nbsp; I was wondering if anyone could look 
> over the following code and give me any suggestions or criticisms?&nbsp; I just 
> started learning Python a few days ago, so I'm sure there's a lot that can be 
> done to make it look and run better.</FONT></DIV>

Please omit the HTML part. Thanks!


Thorsten