I have often read about how important clear and efficient code is. Also often people talk and write about 'beautiful' code. Some hints and critic from experienced developers for the following code would be extremely helpful to me. Another question that I often ask myself is about list comprehensions: I feel that in the first specific code (about prime palindromes), especially the second function that verifies palindrome characteristics could be expressed on one line in a list comprehension - how would that work, and would it even be an advantage of some sort?
The code calculates all the prime palindromes from 0 to 1000 and prints the largest.
#My solution to codeval challenge Prime Palindrome. AUTHOR: S.Spiess
#initial count
counting_list = [x for x in range(0,1001)]
#prime number check. make list prime_list containing only primes from 0 to 1000
def prime_check(a_list):
prime_list = []
for k in a_list:
count = 2.0
d_test = 0
while count < k:
if k % count == 0:
d_test += 1
count += 1
else:
count += 1
if d_test < 1 and k > 1:
prime_list.append(k)
return prime_list
#check prime numbers from previous function for palindrome characteristic. append in new list.
def palindrome_check(num_list):
palindrome_list = []
for i in num_list:
temp = str(i)
if temp == temp[::-1]:
palindrome_list.append(i)
return palindrome_list
#print biggest palindrome prime from 0 to 1000
print max(palindrome_check(prime_check(counting_list)))
I updated my my algorithm for calculating primes, let me know what I could improve!
def hoop(n):
import math
sieve = [False, False] + [True] * (n-1)
for count in xrange(2, int(math.sqrt(n))+1):
if sieve[count]:
for m in xrange(2*count, n+1, count):
sieve[m] = False
return [i for i, s in enumerate(sieve) if s]