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

Find four digit numbers from a string and then print numbers which are primes

I have this code to find four digit numbers from a string:

import re
pattern = re.compile(r"[1-9]\d{3}")
numbers = '0922035963126927190699198371937793731321758941428'
four_digits = pattern.findall(numbers)

My output is:

['9220', '3596', '3126', '9271', '9069', '9198', '3719', '3779', '3731', '3217', '5894', '1428']

And then from output list I want to print only prime numbers. I tried using this code:

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

def prime_factor(four_digits):
prime = []
for i in four_digits:
    flag = 0
    if i==1:
        flag=1
    for j in range(2,i):
        if i%j == 0:
            flag = 1
            break
    if flag ==0:
        prime.append(i)            
return prime

But it returns as an error:

line 13, in prime_factor
for j in range(2,i):

TypeError: 'str' object cannot be interpreted as an integer

What am I doing wrong and is there a better way to do this task?

>Solution :

Replace:

four_digits = pattern.findall(numbers)

by:

four_digits = [int(p) for p in pattern.findall(numbers)]

to convert your list of strings to a list of int.

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