frustrated stupid newbie question
Huaiyu Zhu
huaiyu at gauss.almadan.ibm.com
Wed Mar 13 17:11:50 EST 2002
On Tue, 12 Mar 2002 16:59:13 -0600, Scott Kurland <skurland at juggler.net> wrote:
>Why isn't this $%^*#$% program working?
Others have pointed out what went wrong. Here's a technique that you could
use to find it out yourself, at least for simple programs like this: You put
print statements in the program to see if your expectations are satisfied.
Here's your program, slightly modified, with a few 'print' statements
sprinkled here and there:
#Searching for perfect numbers
import operator
howhigh = input ("How high should I check?")
for number in range(1, howhigh):
factorsum = 0
print number, ':',
for factor in range(1, number/2):
if number % factor == 0:
factorsum += factor
print factor,
if number == factorsum:
print ' ** ', number
else:
print ' -- ', factorsum
The result is:
How high should I check?30
1 : -- 0
...
5 : 1 -- 1
6 : 1 2 -- 3
7 : 1 -- 1
...
23 : 1 -- 1
24 : 1 2 3 4 6 8 ** 24
25 : 1 5 -- 6
26 : 1 2 -- 3
27 : 1 3 9 -- 13
28 : 1 2 4 7 -- 14
29 : 1 -- 1
It got a wrong one, 24, while missing the right ones, 6 and 28. Examining
the factors it found, you can see that the last factor, number/2, is
missing. Now you can open a Python interpreter and test:
>>> range(1,6/2)
[1, 2]
>>> range(1,6/2+1)
[1, 2, 3]
This is something you did not expect, so you could have asked why this is
so, instead of what went wrong in the original program.
In any case, modifying the relevant line above to
for factor in range(1, number/2+1):
produces the expected result:
How high should I check?30
1 : -- 0
2 : 1 -- 1
3 : 1 -- 1
4 : 1 2 -- 3
5 : 1 -- 1
6 : 1 2 3 ** 6
7 : 1 -- 1
8 : 1 2 4 -- 7
9 : 1 3 -- 4
10 : 1 2 5 -- 8
11 : 1 -- 1
12 : 1 2 3 4 6 -- 16
13 : 1 -- 1
14 : 1 2 7 -- 10
15 : 1 3 5 -- 9
16 : 1 2 4 8 -- 15
17 : 1 -- 1
18 : 1 2 3 6 9 -- 21
19 : 1 -- 1
20 : 1 2 4 5 10 -- 22
21 : 1 3 7 -- 11
22 : 1 2 11 -- 14
23 : 1 -- 1
24 : 1 2 3 4 6 8 12 -- 36
25 : 1 5 -- 6
26 : 1 2 13 -- 16
27 : 1 3 9 -- 13
28 : 1 2 4 7 14 ** 28
29 : 1 -- 1
Huaiyu
More information about the Python-list
mailing list