G+_jerry coffey Posted April 14, 2014 Share Posted April 14, 2014 Here is another Python program, determining factors of a number. I did this to practice with adding numbers to list and using for loops. Let me know how I could be better. :) https://github.com/jcoffey42/coding101/blob/master/project2014-P002 Link to comment Share on other sites More sharing options...
G+_Nevrin O Posted April 14, 2014 Share Posted April 14, 2014 add a raw_input() to the end so it doesn't close (on us windows users) before you can read it. otherwise, Good Job! Link to comment Share on other sites More sharing options...
G+_jerry coffey Posted April 14, 2014 Author Share Posted April 14, 2014 Thanks, Nevrin O made that change and will remember to add it in the future. Link to comment Share on other sites More sharing options...
G+_Darryl Medley Posted April 14, 2014 Share Posted April 14, 2014 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 More sharing options...
Recommended Posts