There is a question on codewars, life without primes. I solved it yet the time issue comes up. I really cannot find a better way. The instructions go like;
Consider an array that has no prime numbers, and none of its elements has any prime digit. It would start with: [1,4,6,8,9,10,14,16,18,..]. The element at index 1 is 4.
There will be given an integer n and the task will be return the number at that index in the array. For example, solve(1) = 4, as explained above.
Here is my solution
def solve(n):
no_primes=[]
a=1
if n == 1:
return 4
else:
while True:
try:
no_primes[n]
break
except IndexError:
if is_prime(a) == True:
if is_num_prime(a) == False:
no_primes.append(a)
a=a+1
return no_primes[n]
def is_prime(num):
numbers = list(map(int, list(str(num))))
#primes=[0,2,3,5,7,9]
non_primes=[0,1,4,6,8,9]
return all(list(map(lambda x:x in non_primes,numbers)))
def is_num_prime(num):
if num == 2:
return True
elif num >2:
for i in range(2,num):
if num%i == 0:
return False
else:
return True
else:
return False
Getting rid of the while loop could help but I need to keep on appending until I can reach the value from the list. A recursive for loop with using range(1,n) where n increases recursively may be an option but I could not write it anyways.
numare 2 things which will immensely speed this up.list(map(int, list(str(num))))) while it is not needed. If your next step takes an iterable as input, there is no need for this