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 :-)