[Tutor] python question

Alan Trautman ATrautman at perryjudds.com
Mon Dec 8 17:28:23 EST 2003


Hi,

I wasn't sure what you were trying to do so I played with your program. I
now prints all factor of a number entered. You problem stemmed from the used
of the delete command. When you deleted the number you still incremented the
counter. There would then be nothing to compare when the loop got to the end
and it would appear to skip numbers. I commented where I made the change. 


import string

num_str=raw_input('Enter a number:')

num_num=string.atoi(num_str)

fac_list=range(1,num_num+1)
print "BEFORE:", `fac_list`

i=0

while i < len(fac_list):
    #print "During:  ", num_num % fac_list[i], num_num, fac_list[i]
    if num_num % fac_list[i] <> 0:
        del fac_list[i]
# This is the new section ensure the counter is not incremented 
# when an item is deleted
    else:
        i=i+1
    

    
print "AFTER:", `fac_list`


-----Original Message-----
From: trypticon at SAFe-mail.net [mailto:trypticon at SAFe-mail.net]
Sent: Monday, December 08, 2003 4:10 PM
To: tutor at python.org
Subject: [Tutor] python question


Hi,
   i have a simple question. here is the code:

import string

num_str=raw_input('Enter a number:')

num_num=string.atoi(num_str)

fac_list=range(1,num_num+1)
print "BEFORE:", `fac_list`

i=0

while i < len(fac_list):
      if num_num % fac_list[i]==0:
              del fac_list[i]
       
       i=i+1
print "AFTER:", `fac_list`

there is a bug in this program. i know what the bug is(doesn't work
correctly when you enter an even number), but i'm not sure how to solve it.
Can anybody give me a few hints? Thanks!

_______________________________________________
Tutor maillist  -  Tutor at python.org
http://mail.python.org/mailman/listinfo/tutor



More information about the Tutor mailing list