Hi, I’m trying this python script to get it to run through a list of input values x, and then output a true or false for each number in the input list.
I started with the code provided in this topic:
I changed the code to this:
def primes(n):
results = []
n=int(x)
if n <= 1: results.append("False")
if n>1:
for i in range(2, n//2):
if(n % i) == 0:
results.append("False")
break
else:
results.append("True")
else:
results.append("False")
return results
a = primes(x)
It does output a list, but I’m not getting the correct answers, is there anything I’m missing? I’ve been looking at this for over three hours and my coding isn’t strong so I throw in the towel
In your code you are building an array “results” for each single number to test.
Why?
Your number is prime or not, a single output is enough.
(For your 421 inputs you are getting 423 outputs…)
Also, normally you would build a list of prime numbers iteratively, once, save the list, and use that same list to test all your input numbers.
Instead, for every of your number “n”, this code is iterating n/2 times… totally not optimized:
def IsPrime(n):
if n<1: return("False")
if n==1:return ("True")
if n>1:
for i in range(2, n//2+1):
if(n % i) == 0:
return("False")
break
return("True")
a = IsPrime(x)
Wow, that IAC component did it! With a little change I could make the Python script work as well. Need to declare n = int(n)
I did google on food4rhino and ‘prime’ but it didn’t show me this one. Wow, great tip, also way faster than doing it in Python (1 sec in Python equals around 100ms in the IAC component). Thanks a lot, super valuable tip.
p = []
for num in range(s, e + 1):
# all prime numbers are greater than 1
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
p.append(num)