[Tutor] Re: newbie looking for code suggestions

Bob Roher shiska@swbell.net
Mon, 23 Sep 2002 00:12:38 -0500


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

Sorry.

> 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-

Thanks, I've gotten the chance to look at the first one so far.  I'll check
the other
two out when I get a chance tomorrow.

> 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-
>
> >>> min_number, max_number, digit_total = 1, 999999, 21
> >>> len(quotient_set(range(min_number, max_number+1),
cross_sum)[str(digit_total)])
> 39962

Is that a typo on that output, or is that what you actually got?  I got
39662 when I ran it...

> cpu: 28.121, total: 29.832

Neat.  How do you get the cpu and total time to show up?

> Please omit the HTML part. Thanks!

Sorry again.  I thought it was set to plain text.  Is this better?