简体   繁体   中英

Find prime combinations using Python strings

I need to find all the combinations that make a prime number in a string.

Say I had passed in the string 32_23, it would return 3 and 4 since 32323 and 32423 are prime numbers

This is my code so far:

def isPrime(n):
 if n < 2:
  return False
 for i in range(2, n):
  if not n % i:
     return False
 return True  

string = input()

for letter in string:
 if letter == "_":
  # Do something here

You need to check the blank space against numbers from 0 to 9. Using your code, it will look like this.

def isPrime(n):
 if n < 2:
  return False
 for i in range(2, n):
  if not n % i:
     return False
 return True  

string = input()
primes = []

for i in range(10):
    if isPrime(int(string.replace("_", str(i)))):
        primes.append(i)

for num in primes:
    print(num)

You can replace _ with number from 0-9 and check with isPrime function :

def comb_prime(s):
    try:
       for i in range(10):
         n=int(s.replace('_',str(i)))
         if isPrime(n):
             return n
    except:
           print 'enter a valid num'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM