[Tutor] python question
Karl Pflästerer
sigurd at 12move.de
Mon Dec 8 17:55:56 EST 2003
An unnamed person wrote:
> 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!
First to the bug.
********************************************************************
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 =- 1
i=i+1
print "AFTER:", `fac_list`
********************************************************************
That would be a correct version of your programm (but not a nice one).
If you delete a item you mustn't increment your index.
But now to the programm.
First: don't use string.atoi
Second: you filter a list so use either filter() or a list
comprehension. Then you programm becomes:
********************************************************************
num_num=int(raw_input('Enter a number:'))
fac_list=range(1,num_num+1)
print "BEFORE:", `fac_list`
print "AFTER:", filter(lambda x: num_num % x != 0, fac_list)
#or
print "AFTER:", [x for x in fac_list if num_num % x != 0]
********************************************************************
IMO that's much more readable.
Karl
--
Please do *not* send copies of replies to me.
I read the list
More information about the Tutor
mailing list