Okay, if this question is a repost, sorry because it's not showing up after the first try for some reason lol. Kay, I finished the problem I that asked for some help on before. Pasted here: http://dpaste.com/1386914/ It works fine, but if anyone has any comments or suggestions, especially on how to simplify things, please do post!
And by the way, the problem itself was: Write a program that computes and prints the 1000th prime number.
You can test less numbers. First, if you test %2==0 and get true, it is not prime. Well, other than 2 itself. Then you can test only odd numbers. This will make it run faster for larger values. Also, you only need to test from x to (n+1)/2. Anthing past that would have been divided by a number before it!
Okay, I'm trying to apply this stuff into my code. Thanks for your help so far. Can't believe I forgot about the odds only when I was tinkering with it for a long time lol Gotta go pretty much right now but planning to post my edited code when I have time.
Another thing you can do is not save all the primes you don't need... only need the last one, so the rest can be tossed.
usually a function takes an argument and returns something. the code that calls the function then uses the thing that is returned. your implementation relies on a side affect - isprime is modifies primes directly and does not return anything. while this works it doesn't seem kosher. because it doesn't return a value and relies on a side affect, you have this funny looking statement at line 16 - when i or someone else reads it we wouldn't know what it is doing. isprime tests a number for primeness - perhaps it should just return True or False - then you can write a conditional statement like ``` if isprime(n): # do something - maybe append it to primes ``` that is much cleaner ands anyone reading will know what it does
``` >>> def is_black(color): if color == 'black': return True return False >>> color = 'red' >>> >>> if is_black(color): print 'yes!!' else: print 'no way!' no way! >>> ```
.bwCA- thanks so much! wish i could give two medals :P i knew the content of actual functions still needed work but i also felt like something was seriously lacking in how i was going about the whole thing and i couldn't put it into words. that's why i commented everything, because though it does what it's supposed to, it's just not easy to read or figure out my logic, i guess. i think i'm going to start over again and try to be simpler.
giving your functions descriptive names can go a long way to making your code readable.
Join our real-time social learning platform and learn together with your friends!