Here's the question you clicked on:
LoveMathFermat
Hello! I just finished the very first problem on problem set 1 thanks to you guys. What do you think of the code I wrote? I am a starter. I would like to know if I am on the right direction or developing some bad habit. Any advice would be greatly appreciated candidates=range(3,10000,2) prime=() i=0 while (i<4999): x = 2 dec=0 while (x<candidates[i]): if candidates[i]%x == 0: x=x+1 dec=dec+1 else: x=x+1 if dec>0: i=i+1 else: prime=prime+(candidates[i],) i=i+1 print prime[998] and I got the right answer which is 7919. Thanks in advance!
hey - it's nice.... you can speed and clean it a little: candidates = range(3, 10000, 2) prime = [] # i have no real reason to choose a list -[]-over a tuple-(), maybe faster i = 0 while i < 4999: ....x = 2 ....dec = 0 ....while x <= candidates[i] // 2: # can't be > candidates[i]/2 ........if candidates[i] % x == 0: ............dec = dec + 1 ........x = x + 1 # this is done in any case.... ....if dec == 0: # saves an else ........prime.append(candidates[i]) # this is where list maybe faster- []- instead of () ....i = i + 1 # could write i += 1, same thing.but is always done here print (prime[998]) of course, your code is good - it works! There's not even a whole nit to pick on... ( how do you get indents to work here? )
One thing that you'll regret in a month or two is that some of your variable names aren't too descriptive, and there aren't any comments. FWIW, I've been writing my comments first to frame out my functions.
Thank you guys! I really appreciate your advice! To snark, I just copied and pasted the code directed from python. It should work for you !