Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

python - How do i implement these algorithms below

Alogrithm 1:

Get a list of numbers L1, L2, L3....LN as argument
Assume L1 is the largest, Largest = L1
Take next number Li from the list and do the following
If Largest is less than Li
Largest = Li
If Li is last number from the list then
return Largest and come out
Else repeat same process starting from step 3

Algorithm 2:

Create a function prime_number that does the following
Takes as parameter an integer and
Returns boolean value true if the value is prime or
Returns boolean value false if the value is not prime

So far my code is :

def get_algorithm_result(num_list):    
    largest =num_list[0]        
    for item in range(0,len(num_list)):    
        if largest < num_list[item]:                
            largest = num_list[item]    
    return largest

def prime_number(integer):    
    if integer%2==0:
        return False
    else:
        return True

After executing the code i get

"Test Spec Failed

Your solution failed to pass all the tests" 

where am I going wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Is what you mean with the first one find the largest number? Then you should use max() like

list = [1,2,4,5,3]
print max(list)
>>> 5

This should help with the second one:

def prime_number(n):

    if n > 1:
       for x in range(2,n):
           if (n % x) == 0:
               return False
               break
       else:
           return True

If a number is prime, then the factors are only 1 and itself. If there is any other factor from 2 to the number, it is not prime. n % x finds the remainder when n is divided by x. If x is a factor of n, then n % x has a remainder of 0.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...