Help to streamline Prime Number Finder code - Python

Hello,

I finished Beginner Python3, and felt I had a pretty good grasp of the concepts. I succeeded in completing the Prime Number Finder Python Code Challenge after several hours, but it legit took hours. I was so happy, until I compared my code with other users’.

I’m wordy in real life, I guess it’s no surprise it takes twice the code for me than it takes for my peers, but I’m a little concerned at HOW different my stuff is.

All advice on the code itself, drawing straighter lines conceptually, less is more, or just some kind words are all appreciated. Thank you.

Link to Everyone Else’s Code (except mine, I’m not posting my novel there…)
https://discuss.codecademy.com/t/python-challenge-prime-number-finder/627801

My code

def prime_finder(n): # Write your code here n = int(n) outgoing_primes = [] ######FUNCTIONS###### # 6K +- 1 Theory Populator def populator(n): for number in range(1, n): temp_no = (6*number) lo_hi = [(temp_no - 1), (temp_no + 1)] lo = lo_hi[0] hi = lo_hi[1] lo_hi_tester(lo, hi) if hi >= n: break # pass/fail prime number tester def lo_hi_tester(lo, hi): # to test low input value lo_test = 0 for prime in outgoing_primes: if lo % prime == 0: lo_test += 1 if lo_test == 0: outgoing_primes.append(lo) # to test high input values hi_test = 0 for prime in outgoing_primes: if hi % prime == 0: hi_test += 1 if hi_test == 0: outgoing_primes.append(hi) # output trimmer def popper(list_name, index): if index <= list_name[-1]: list_name.pop() #########CODE######### if n < 2: return "There are no prime numbers in that range." elif n == 2: outgoing_primes += [2] elif n < 5: outgoing_primes += 2, 3 else: outgoing_primes += [2, 3, 5] populator(n) while outgoing_primes[-1] > n: popper(outgoing_primes, n) return outgoing_primes
1 Like

Hi,

Problems like efficient complexity for finding prime numbers fall under the category of numerical methods… which you might find in a maths curriculum before a c.s. one.
Since it’s a different discipline altogether, the more optimal answers might seem like very foreign and arbitrary. Usually the people that do these problems are the ones that seek them specifically. So don’t be disheartened!

1 Like

Hello!
I wouldn’t get too downhearted. Yours looks like a much more nuanced answer, and I’d wager will run a lot quicker than a fair few that have been posted.
There’s probably some bits you could tweak, but that’s part of the fun.
As I mentioned in my entry, I’ve done this or something like it a few times and usually end up with something different depending on how I attack it.

Happy coding.

1 Like

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.