Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Print out a list of prime numbers in python

The question is: print out all numbers from 1 to 1000 that satisfy the two conditions:

  1. Those are prime numbers
  2. The numbers after being reversed are also prime numbers.
    e.g., 13 satisfies (as 13 and 31 are prime numbers), but 19 does not satisfy (19 is a prime number, while 91 is not).
    My codes:
def prime(n):
  if n<2:
    return False
  for i in range(1, n):
    if n%i == 0:
      return False
  else:
    return True

def reverse(n):
  List = []
  while n>0:
    List.append(n%10)
    n = n//10

  string = [str(integer) for integer in List]
  a_string = "".join(string)
  result = int(a_string)
  print(result)

L = []
for i in range (1, 1000):
  if prime(i) == prime(reverse(i)) == True:
    L.append(i)
print(L)

Mine seems to contain some errors as the outcome is not as expected, either it shows none or still shows 19 in the list.
Thank you in advance!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

First your prime method is wrong, because the loops starts at 1, and every numbre satisfies n%1 == 0 , it needs to starts at 2

def prime(n):
    if n < 2:
        return False
    for i in range(2, n):
        if n % i == 0:
            return False
    return True

Then your reverse method returns nothing so reverse(5) gives None, you have tried it manually.

def reverse(n):
    values = []
    while n > 0:
        values.append(n % 10)
        n = n // 10
    return int("".join(map(str, values)))

Then simplify the condition to be

for i in range(1, 20):
    if prime(i) and prime(reverse(i)):
        L.append(i)

The reverse process can be done with string also, and so short that it can be inlined

L = []
for i in range(1, 20):
    if prime(i) and prime(int(str(i)[::-1])):
        L.append(i)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading