简体   繁体   中英

Largest sequence of prime numbers from array

I'm new to python and I'm trying to figure out the largest sequence of prime numbers from an array. I wrote a function to figure if a number is prime or not and using this I'm trying to find the largest sequence of prime numbers in an array.

For example:

array1 = [1,2,5,4,2,2,3,4]

For this array, the largest sequence of prime numbers is 2,2,3. To figure this I tried using this approach:

def primeSequence(s):
    l=[]
    k=[]
    j=0
    for i in range(1,len(s)+1):

        if isPrime(s[i]):  
            l.append(s[i])
        else:
            break
    print(l)    
    k.append(l)
    print(k);

Basically, I went through the array and check if the number is prime. If it is, I store it in an array. Then that array I store it in another array and in the end the plan was to go through that k array and find which array is the largest.

The problem is that the for loop breaks when it find the 4 (which is not prime) and I don't know how to traverse the array again from that point.. I'm not sure if I was clear enough.. Any suggestions how can I do this? Thanks a lot.

This should do it.

def primeSequence(s):
    l=[]
    k=[]
    j=0
    max_l = []                       #store the max sequence at present

    for i in range(len(s)):

        if isPrime(s[i]):  
            l.append(s[i])
        else:
            if len(l)>len(max_l):     #is longest primeSequence
              max_l = l               #store that
            l=[]                      #for starting new primeSequence series

    if len(l)>len(max_l):             #handles case where the sequence includes the last element
          max_l = l

    print(max_l)

Few things. For finding the max sequence, you need to store the values of the present max sequence in another variable and check if the present sequence len is greater than the max sequence len . The else part is used as a marker that the present prime sequence has ended and this is where you check if what you have now is the greater sequence.

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