简体   繁体   中英

Smallest Positive Number - Python - Codility

I am using Codelite to train myself as I just started learning Python. In the excercise "Smallest Positive Number", I used the code below and some test cases passed, but most of them not. How can I improve my code? (test cases like [1,2,3,4] and repetitive numbers like [5,6,2,4,6].

A = [2,1,-2,5,-6]

m = max(A)
temp = []
index = []
result = []

if m < 1:
    print ("1")
elif len(A) == 1:
    if A[0] == 1:
        print("2")
    else:
        print("1")
else:
    for i in range(len(A)):
        if A[i] > 0:
            temp.append(A[i])
            temp.sort()
    print(temp)
    for j in range(len(temp)):
        index.append(j+1)
        if temp[j] != index[j]:
            result.append(index[j])

    print(min(result))

Thanks!

First you would want to store the smallest positive number. Start it at the first element of the list.

small_positive = A[0]

You would then want to iterate through the input

    for number in A:

Then check if the number is positive. The easiest way is to see if it is greater then zero.

        if number > 0:

After, check if the number is smaller then the current smallest. If so, overwrite it.

            if number < small_positive:
                small_positive = number

Lastly, you need to check if there were all negatives in the list. If small_positive is negative after the loop, there were no positives in the list.

if small_positive < 0:
    return None

This is the easiest way to understand the solution, but there are many built in functions which are much simpler then this.

For a start, this wouldn't work for the list [-42] :

m = max(A)
if m < 1:
    print ("1")

There's no 1 anywhere in that given list so it should not be reported as the solution. Python would usually give you None in that scenario but the puzzle you've been set may have other ideas. It also wouldn't work with the list [] as max() will complain bitterly about the empty list.

You may think that one or both of those cases are unlikely but that's one of the things that makes the difference between a good coder and a not-so-good one. The former assume their users and testers are psychotic geniuses who know how to break code with near-zero effort :-)


To code it up by yourself, you can use the following pseudo-code (1) as a basis:

num_list = (some list of numbers)
min_pos = nothing
for num in num_list:
    if num > 0 and (min_pos is nothing or num < min_pos): # >= ?
        min_pos = num

print(min_pos)

Of course, if you're learning Python rather than learning programming, you should probably just use the facilities of the language, things will be much easier:

pos_list = [item for item in the_list if item > 0] # >= ?
min_pos = min(pos_list) if len(pos_list) > 0 else None
print(min_pos)

And, if you consider zero to be positive, make sure you use >= 0 instead of > 0 , in both code blocks above where indicated.

Both of these snippets will successfully handle lists with no positive numbers, giving you a sentinel value (Python None or pseudo-code nothing ).


(1) Yes, it looks a bit like Python but that's only because Python is the ultimate pseudo-code language :-)

A = [2,-2,5,-6]



def small(a,b):
    if a >= b: return b
    else: return a




positive_list = [ele for ele in A if ele > 0]
res = min(positive_list)


if len(positive_list) == 0:
    print("no positive number.")
else:
    for i in range(len(positive_list)):
        res = small(res, positive_list[i])

print(f"Smallest Positive number : {res}")

by this, yon can easily get a result.

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