Jump to content

Here is another Python program, determining factors of a number


G+_jerry coffey
 Share

Recommended Posts

Your program is well structured but there are a number of optimizations that you can make:

- the fac and findex variables are not needed. fac is not needed because x in the for loop has the same value. findex is not needed because you don't need an index to add to a list. Just use myList.append(value_to_add).

- your "range" is wrong. The second param in range must be one higher than the last value you want. range(1,5) only gives you the numbers 1,2,3,4. If you want the numbers 1-5 you must say range(1,6). Confusing - I know.

 

So your main loop can just be:

for x in range(1,num+1) :  # * Note "num+1"

    if num % x == 0: 

        print "A factor is: ", x       

        Factors.append(x) 

 

- Bonus fact 1: You don't need to use int(some_number) when assigning a number to a variable. Python knows it's a number instead of a string because it doesn't have quotes around it. Just use i = 0.

 

- Bonus fact 2: Python has some really powerful list functions that let you create a list like this with one line of code:

num = int(raw_input("Enter a number: ")) 

print "Factors", filter(lambda x: num % x == 0, range(1,num + 1))

raw_input("(press Enter to close)")

Link to comment
Share on other sites

 Share

×
×
  • Create New...