Ask your own question, for FREE!
MIT 6.00 Intro Computer Science (OCW) 18 Online
OpenStudy (anonymous):

For PS1b, I'm looking to check my answers. What's the best way to go about doing this?

OpenStudy (anonymous):

ask a question and share your code. we will take a look and provide feedback.

OpenStudy (anonymous):

Thanks malpaso, I wasn't sure what the best procedure is. I think I got it right... I pasted my code here: http://dpaste.com/686872/

OpenStudy (anonymous):

The code looks correct. Nicely done. You generate the set of primes correctly and the ratio approaches 1 as n increases. So others can learn from your example, can you please explain the statement for divisor in range(3,(test_num+3)/3): It's a for loop where divisor ranges from 3 to (test_num+3)/3. What's the logic there? Again, good job.

OpenStudy (anonymous):

Well, the smallest number a odd number can be divisible by is 3. We also need to make the number slightly larger to take into account all the factors. Since we are dividing it by 3, the smallest numbers, 3, 5, keep the loop from running more than once. Increasing it makes it work... or so I surmise.

OpenStudy (maitre_kaio):

While I was debugging your code with print statements because I had the feeling something was wrong, I had a hard time with your for loop. And then I discovered that you were using a for... else loop ( http://docs.python.org/ref/for.html). Amazing ! I didn't even know such a structure existed, since I never saw that structure in any other language I studied ! Now I understand your program better :) Just a suggestion though: i think you should test test_num <= num_n instead of test_num < num_n, because if you enter a prime number, it won't be tested. Also, you could have a lot less iterations in the loop if, instead of range(3,(test_num+3)/3), you put range(3,int(sqrt(test_num)) + 1) That said, thanks, I learned something because of you!

OpenStudy (anonymous):

Thanks maitre_kaio, I saw it while looking over someone elses code on solutions to this PS. Do you have any suggestions how best to do it without this For Else type loop?

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!