[英]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 假设我传入了字符串32_23,由于32323和32423是质数,它将返回3和4
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. 您需要对照0到9之间的数字检查空格。使用您的代码,它将看起来像这样。
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 : 您可以将
_
替换为0-9之间的数字,并使用isPrime
函数进行检查:
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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.